标签:
paramiko模块,基于SSH用于连接远程服务器并执行相关操作。
pip3 install paramiko
2.1 SSHClient
用于连接远程服务器并执行基本命令
用户名,密码:SSHClient,Transport
import paramiko # 创建SSH对象 ssh = paramiko.SSHClient() # 允许连接不在know_hosts文件中的主机 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接服务器 ssh.connect(hostname=‘192.168.101.11‘, port=22, username=‘root‘, password=‘123456‘) # ssh.connect(hostname=‘192.168.11.61‘, port=22, username=‘alex‘, password=‘alex3714‘) # 执行命令 stdin, stdout, stderr = ssh.exec_command(‘ls‘) # 获取命令结果 result = stdout.read() print(result) # 关闭连接 ssh.close()
用户名、密码:Transprot
import paramiko import uuid class SSHConnection(object): def __init__(self, host=‘192.168.101.11‘, port=22, username=‘root‘,pwd=‘123456‘): self.host = host self.port = port self.username = username self.pwd = pwd self.__k = None def run(self): self.connect() pass self.close() 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 cmd(self, command): ssh = paramiko.SSHClient() ssh._transport = self.__transport # 执行命令 stdin, stdout, stderr = ssh.exec_command(command) # 获取命令结果 result = stdout.read() return result def upload(self,local_path, target_path): # 连接,上传 sftp = paramiko.SFTPClient.from_transport(self.__transport) # 将location.py 上传至服务器 /tmp/test.py sftp.put(local_path, target_path) ssh = SSHConnection() # 打开连接 ssh.connect() # 执行命令 r1 = ssh.cmd(‘df‘) print(r1) ssh.upload(‘s2.py‘, "/root/s7.py") # 关闭连接 ssh.close()
标签:
原文地址:http://www.cnblogs.com/liangdalong/p/5742826.html