paramiko模块基于ssh,用于连接远程服务器并执行相关操作。
sshclient:用于连接远程服务器并执行基本命令:
import paramiko# 创建ssh对象ssh = paramiko.SSHClient()# 允许连接不在know_hosts文件中的主机ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())# 连接服务器ssh.connect(hostname='192.168.254.130', port=22, username='root', password='123456')# 执行命令stdin, stdout, stderr = ssh.exec_command('service iptables stop')# 获取命令执行结果result = stdout.read()print(result.decode())# 关闭连接ssh.close()
import paramikotransport = paramiko.Transport(('192.168.254.129', 22))transport.connect(username='root', password='123456')ssh = paramiko.SSHClient()ssh._transport = transportstdin, stdout, stderr = ssh.exec_command('df;ls')res, err = stdout.read(), stderr.read()reslt = res if res else errprint(reslt.decode())ssh.close()
import paramikotrans = paramiko.Transport(('192.168.33.128', 22))trans.connect(username='root', password='123456')sftp = paramiko.SFTPClient.from_transport(trans)sftp.put('test', '/tmp/test') #第一个参数是上传的文件及路径,第二个参数是服务器的路径及名称sftp.get('/root/test/ftptest', 'p') #第一个是下载的路径及名称,第二个参数是本地的路径及名称trans.close()
import paramiko private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa') # 创建SSH对象ssh = paramiko.SSHClient()# 允许连接不在know_hosts文件中的主机ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())# 连接服务器ssh.connect(hostname='c1.salt.com', port=22, username='wupeiqi', key=private_key) # 执行命令stdin, stdout, stderr = ssh.exec_command('df')# 获取命令结果result = stdout.read() # 关闭连接ssh.close()
import paramikofrom io import StringIOkey_str = """-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAq7gLsqYArAFco02/55IgNg0r7NXOtEM3qXpb/dabJ5Uyky/8NEHhFiQ7deHIRIuTW5Zb0kD6h6EBbVlUMBmwJrC2oSzySLU1w+ZNfH0PE6W6fansH80whhuc/YgP+fjiO+VR/gFcqib8Rll5UfYzf5H8uuOnDeIXGCVgyHQSmt8if1+e7hn1MVO1Lrm9Fco8ABI7dyv8/Z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JpQK8fPwVxRxbJS/pMbNICrf3sUa4sZgDOFfkeuSlgACh4cVIozDXlR59Z8Y3CoiW0uObEgvMDIfenAj98pl3ZkCgYEAj/UCSni0dwX4pnKNPm6LUgiS7QvIgM3H9piyt8aipQuzBi5LUKWwDlQC4Zb73nHgdREtQYYXTu7p27Bl0Gizz1sW2eSgxFU8eTh+ucfVwOXKAXKU5SeI+MbuBfUYQ4if2N/BXn47+/ecf3A4KgB37Le5SbLDddwCNxGlBzbpBa0=-----END RSA PRIVATE KEY-----"""private_key = paramiko.RSAKey(file_obj=StringIO(key_str))transport = paramiko.Transport(('10.0.1.40', 22))transport.connect(username='wupeiqi', pkey=private_key)ssh = paramiko.SSHClient()ssh._transport = transportstdin, stdout, stderr = ssh.exec_command('df')result = stdout.read()transport.close()print(result)