python模块paramiko的上传下载和远程执行命令方法
用python实现远程登陆主机执行命令或通过sftp上传下载文件,有个很好的模块paramiko模块来演示这些功能,使用起来很方便,大家可学习一下。写了几个小程序,用于说明此模块的使用方法。
查看python的安装目录
$> which python
/usr/bin/python
1:连接远程linux主机并执行命令
前提条件:必须安装python和paramiko模块
pythonDemo.sh的内容如下:
#!/usr/bin/python
import paramiko
hostname='192.168.10.12'
username='root'
password='root'
port=22
paramiko.util.log_to_file('paramiko.log')
s=paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect(hostname = hostname,port=port,username=username, password=password)
stdin,stdout,stderr=s.exec_command('free;df -h')
print stdout.read()
s.close()
执行结果如下:
$>chmod +x pythonDemo.sh
./pythonDemo.sh
total used free shared buffers cached
Mem: 2074940 2057420 17520 0 42416 1867968
-/+ buffers/cache: 147036 1927904
Swap: 2096472 240 2096232
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 30G 12G 17G 42% /
none 1014M 0 1014M 0% /dev/shm
/dev/sda3 2.0G 289M 1.6G 16% /var
/dev/sdb1 135G 14G 115G 11% /data
/dev/sdc1 135G 127G 880M 100% /data1
/dev/sdd1 135G 99G 30G 78% /data2
2:连接远程linux主机上传下载文件(paramiko模块是用SFTP协议来实现的)
前提条件:必须安装python和paramiko,datetime,os模块
#!/usr/bin/python
import paramiko,datetime,os
hostname='192.168.0.102'
username='root'
password='abc123'
port=22
local_dir='/tmp/'
remote_dir='/tmp/test/'
try:
t=paramiko.Transport((hostname,port))
t.connect(username=username,password=password)
sftp=paramiko.SFTPClient.from_transport(t)
#files=sftp.listdir(dir_path)
files=sftp.listdir(remote_dir)
for f in files:
print ''
print '#########################################'
print 'Beginning to download file from %s %s ' % (hostname,datetime.datetime.now())
print 'Downloading file:',os.path.join(remote_dir,f)
sftp.get(os.path.join(remote_dir,f),os.path.join(local_dir,f))#下载
#sftp.put(os.path.join(local_dir,f),os.path.join(remote_dir,f))#上传
print 'Download file success %s ' % datetime.datetime.now()
print ''
print '##########################################'
t.close()
except Exception:
print "connect error!"
执行结果:
还有好多用法,具体的可以看官方文档:http://www.lag.net/paramiko/docs/
如何没有安装对应的模块,运行将报错,比如第一个例子:
$>./pythonDemo.sh
Traceback (most recent call last):
File "./pythonDemo.sh", line 2, in ?
import paramiko
ImportError: No module named paramiko
来源参考网络
python-paramiko-upload-and-download--and-remote-execute-demo