python 远程执行命令、上传、下载举例

使用python中的 paramiko 实现远程操作,需要安装 paramiko 模块。

# vi pssh.py

#!/usr/bin/python
#coding=utf-8 '''
Created on Apr 13, 2016 @author: root
''' import paramiko class PSSH(): def __init__(self,ip,sort,username,password): self.ip = ip
self.sort = sort
self.username = username
self.passwrod = password def exec_cmd(self,cmd):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#ssh.connect(hostname, port, username, password, pkey, key_filename, timeout, allow_agent, look_for_keys, compress, sock)
ssh.connect(self.ip,self.sort,self.username,self.passwrod)
stdin,stdout,stderr = ssh.exec_command(cmd)
print stdout.readlines()
ssh.close() def upfile(self,localpath,remotepath):
'''
'''
t = paramiko.Transport((self.ip,self.sort))
t.connect(username= self.username,password=self.passwrod)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put(localpath,remotepath)
t.close() def downfile(self,remotepath,localpath):
'''
'''
t = paramiko.Transport((self.ip,self.sort))
t.connect(username= self.username,password=self.passwrod)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get(remotepath,localpath)
t.close() if __name__ == '__main__': pssh = PSSH("192.168.1.77",22,"oracle","oracle");
# pssh.exec_cmd("cat /tmp/a.txt")
#pssh.upfile("/tmp/1.txt", "/tmp/1.txt")
pssh.downfile("/tmp/a.txt", "/tmp/a.txt") print '------success!-----'

测试下载功能

# chmod +x pssh.py
# ./pssh.py
------success!-----
# ll | grep a.txt
-rw-r--r--. 1 root root 4 Apr 13 10:16 a.txt
上一篇:bootstrap Table 中给某一特定值设置table选中


下一篇:[51NOD1087]1 10 100 1000(规律,二分)