首页 > 代码库 > Python paramiko

Python paramiko

paramiko有两个模块SSHClient()和SFTPClient()

利用SSHClient()

#coding:utf-8import paramiko#创建SSH对象ssh = paramiko.SSHClient()# 允许连接不在know_hosts文件中的主机ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())# 连接服务器ssh.connect(hostname=192.168.2.103, port=22, username=root, password=123456)# 执行命令stdin, stdout, stderr = ssh.exec_command(ls)# 获取命令结果result = stdout.read()print (str(result,encoding=utf-8))# 关闭连接ssh.close()

SSHClient()里面有一个transport变量,这个是用于获取连接的,因此我们也可以单独的获取到transport变量,然后执行连接操作

#coding:utf-8import paramikotransport = paramiko.Transport((192.168.2.103, 22))transport.connect(username=root, password=123456)ssh = paramiko.SSHClient()ssh._transport = transportstdin, stdout, stderr = ssh.exec_command(df)print (str(stdout.read(),encoding=utf-8))transport.close()

SFTPClient()也是使用transport来实现的,因此如果有需求需要执行命令和上传文件糅合在一起的话,那么就需要使用transport的方式来实现。

用transport实现上传下载以及命令的执行:

#coding:utf-8import paramikoimport uuidclass SSHConnection(object):    def __init__(self, host=192.168.2.103, port=22, username=root,pwd=123456):        self.host = host        self.port = port        self.username = username        self.pwd = pwd        self.__k = None    def connect(self):        transport = paramiko.Transport((self.host,self.port))        transport.connect(username=self.username,password=self.pwd)        self.__transport = transport    def close(self):        self.__transport.close()    def upload(self,local_path,target_path):        # 连接,上传        # file_name = self.create_file()        sftp = paramiko.SFTPClient.from_transport(self.__transport)        # 将location.py 上传至服务器 /tmp/test.py        sftp.put(local_path, target_path)    def download(self,remote_path,local_path):        sftp = paramiko.SFTPClient.from_transport(self.__transport)        sftp.get(remote_path,local_path)    def cmd(self, command):        ssh = paramiko.SSHClient()        ssh._transport = self.__transport        # 执行命令        stdin, stdout, stderr = ssh.exec_command(command)        # 获取命令结果        result = stdout.read()        print (str(result,encoding=utf-8))        return resultssh = SSHConnection()ssh.connect()ssh.cmd("ls")ssh.upload(s1.py,/tmp/ks77.py)ssh.download(/tmp/test.py,kkkk,)ssh.cmd("df")ssh.close()

 

Python paramiko