浪子huang 2019-06-27
paramiko是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件操作,值得一说的是,fabric和ansible内部的远程管理就是使用的paramiko来现实。
pycrypto,由于 paramiko 模块内部依赖pycrypto,所以先下载安装pycrypto
yum -y install python-devel pip3 install pycrypto pip3 install paramiko
import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('172.16.0.10', 22, 'root', '123456') stdin, stdout, stderr = ssh.exec_command('df -hT') print(stdout.read().decode('utf-8')) # 以utf-8编码对结果进行解码 ssh.close()
# 上传文件 import os import sys import paramiko t = paramiko.Transport(('172.16.0.19', 22)) t.connect(username='root', password='123456') sftp = paramiko.SFTPClient.from_transport(t) sftp.put('log.log', '/tmp/log.log') t.close() # 下载文件 import os,sys import paramiko t = paramiko.Transport(('172.16.0.19',22)) t.connect(username='root', password='123456') sftp = paramiko.SFTPClient.from_transport(t) sftp.get('/tmp/log.log', 'log2.log') t.close()
import paramiko private_key_path = '/root/.ssh/id_rsa' key = paramiko.RSAKey.from_private_key_file(private_key_path) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('172.16.0.19', 22, 'root', key) stdin, stdout, stderr = ssh.exec_command('df -hT') print(stdout.read()) ssh.close()
# 上传文件 import paramiko pravie_key_path = '/root/.ssh/id_rsa' key = paramiko.RSAKey.from_private_key_file(pravie_key_path) t = paramiko.Transport(('172.16.0.19', 22)) t.connect(username='root', pkey=key) sftp = paramiko.SFTPClient.from_transport(t) sftp.put('log.log','/tmp/log.log') t.close() # 下载文件 import paramiko pravie_key_path = '/root/.ssh/id_rsa' key = paramiko.RSAKey.from_private_key_file(pravie_key_path) t = paramiko.Transport(('172.16.0.19', 22)) t.connect(username='root', pkey=key) sftp = paramiko.SFTPClient.from_transport(t) sftp.get('/tmp/log.log', 'log3.log') t.close()