摘要:
使用密码连接:#!/bin/env python3# _*_ coding:utf-8 _*_# Author: ...
使用密码连接:
#!/bin/env python3 # _*_ coding:utf-8 _*_ # Author: nianzong import paramiko host = '192.168.10.95' port = 22 username = 'root' password = '123456' cmd = 'hostname;ip a' #创建SSH对象 ssh = paramiko.SSHClient() #把要连接的机器添加到known_hosts文件中 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=host,port=port,username=username,password=password,timeout=5) stdin, stdout, stderr = ssh.exec_command(cmd,timeout=3) result = stdout.read() result_err = stderr.read() # if not result: # result = stderr.read() print(result.decode().strip()) print(result_err.decode().strip()) ssh.close()
使用key免密码连接:
#!/bin/env python3 # _*_ coding:utf-8 _*_ # Author: nianzong import paramiko host = '192.168.10.95' port = 22 username = 'root' password = '123456' cmd = 'hostname;ip a' # 使用key免密码登录 private_key = paramiko.RSAKey.from_private_key_file("/root/.ssh/id_rsa") #创建SSH对象 ssh = paramiko.SSHClient() #把要连接的机器添加到known_hosts文件中 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #ssh.connect(hostname=host,port=port,username=username,password=password,timeout=5) ssh.connect(hostname=host,port=port,username=username,pkey=private_key,timeout=5) stdin, stdout, stderr = ssh.exec_command(cmd,timeout=3) result = stdout.read() result_err = stderr.read() # if not result: # result = stderr.read() print(result.decode().strip()) print(result_err.decode().strip()) ssh.close()
使用key的sftp:
#!/bin/env python3 # _*_ coding:utf-8 _*_ # Author: nianzong import paramiko private_key = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa') transport = paramiko.Transport(('192.168.10.95', 22)) #transport.connect(username='root', password='123456') transport.connect(username='root', pkey=private_key) sftp = paramiko.SFTPClient.from_transport(transport) # 将jdk-8u191-linux-x64.tar.gz上传至目标服务器的/tmp下并改名为jdk.tar.gz sftp.put('/root/jdk-8u191-linux-x64.tar.gz', '/tmp/jdk.tar.gz') # 从目标服务器下载 sftp.get('/root/controller', '/tmp/from_controller') transport.close()
还没有评论,来说两句吧...