Python使用paramiko操作linux的方法讲解

yipeiwu_com5年前Python基础

paramiko介绍

paramiko是一个基于python编写的、使用ssh协议的模块,跟xshell和xftp功能类似,支持加密与认证,可以上传下载和访问服务器的文件。

可以利用paramiko模块写服务器脚本,在本地执行,比如持续更新代码,查看日志,批量配置集群等。

paramiko 主要包含SSHClient和SFTPClient两个组件:

SSHClient

ssh服务会话的表示,通常用来执行命令,主要有connect、exec_command、load_system_host_keys和set_missing_host_key_policy方法。

  • connect:建立SSH远程连接并校验。
  • exec_command:执行指令并返回结果。
  • load_system_host_keys:加载本地公钥校验文件。
  • set_missing_host_key_policy:远程主机没有本地主机密钥或HostKeys时的策略。

SFTPClient

SFTP客户端对象,实现远程文件操作,主要有from_transport、put、get、Mkdir、remove、rename、stat、listdir等方法。

  • from_transport:从已通过验证的传输对象简历连接。
  • put:上传本地文件到服务器上。
  • get:从服务器下载文件到本地。
  • Mkdir、remove、rename、stat、listdir:创建目录、删除目录、重命名文件或目录、获取文件信息、获取指定目录中的列表。

安装与使用

安装

pip install paramiko

执行linux命令

import paramiko
#服务器信息,主机名(IP地址)、端口号、用户名及密码
hostname = "xxx.xxx.xx.170"
port = 11022
username = "rdadmin"
password = "818"
#创建SSH对象 
client = paramiko.SSHClient()
#自动添加策略,保存服务器的主机名和密钥信息
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#连接服务器
client.connect(hostname, port, username, password, compress=True)
# 执行linux命令
stdin, stdout, stderr = client.exec_command('ls /')
for line in stdout:
  print('... ' + line.strip('\n')) 
#or
print(stdout.readlines())

访问linux上的文件

import paramiko
hostname = "192.168.0.1"
port = 22
username = "root"
password = "root"
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname, port, username, password, compress=True)
sftp_client = client.open_sftp()
remote_file = sftp_client.open("/home/verified_list.txt") #文件路径
try:
  for line in remote_file:
    print(line.strip())
finally:
  remote_file.close()

上传到linux与从linux下载文件

import paramiko
hostname = 192.168.0.1
port = 22
username = "root"
password = "root"
transport = paramiko.Transport((hostname, port))
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
# 下载文件
sftp.get("/home/share/video.mp4","./视频文件下载/")
#上传文件
sftp.put("./video.mp4","/home/share/video.mp4")
sftp.close()

与linux的交互操作

通过SSHClient的invoke_shell方法,可以创建一个交互会话的对象,和exec_command方法不同的是,这个可以实现命令交互,比如先cd到某个目录下,再执行脚本操作,然后退出,这种需要多个步骤的操作。

import paramiko
hostname = "192.168.0.1"
port = 22
username = "root"
password = "root"
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname, port, username, password, compress=True)
channel = client.invoke_shell() # 在SSH server端创建一个交互式的shell
command = ""
channel.send(command + '\n')
time.sleep(10)
stdout = channel.recv(1024*100000)
out_list = stdout.decode().split("\n")
client.close()

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对【听图阁-专注于Python设计】的支持。如果你想了解更多相关内容请查看下面相关链接

相关文章

对python 中re.sub,replace(),strip()的区别详解

对python 中re.sub,replace(),strip()的区别详解

1.strip(): str.strip([chars]);去除字符串前面和后面的所有设置的字符串,默认为空格 chars -- 移除字符串头尾指定的字符序列。 st = " he...

python图像和办公文档处理总结

python图像和办公文档处理总结

用程序来处理图像和办公文档经常出现在实际开发中,Python的标准库中虽然没有直接支持这些操作的模块,但我们可以通过Python生态圈中的第三方模块来完成这些操作。 操作图像 计算机图...

Python调用C++,通过Pybind11制作Python接口

我是在ubuntu系统进行实验的,所以和window可能会有区别。 python调用C/C++有不少的方法,如boost.python, swig, ctypes, pybind11等,...

Python3多线程操作简单示例

本文实例讲述了Python3多线程操作。分享给大家供大家参考,具体如下: python3 线程中常用的两个模块为: _thread threading(推荐使用) thread 模块已被...

python实现系统状态监测和故障转移实例方法

复制代码 代码如下:#coding: utf-8import socketimport selectimport timeimport osimport threading def se...