Python远程登录Linux操作系统,执行命令、创建目录、上传及下载文件(之二)
远程连接Linux主机,执行命令、创建目录、上传及下载文件
#!/usr/bin/python
#coding:utf-8
import paramiko
from fabric.api import env,put,get
import threading
class Host:
def __init__(self,ip,user,password):
self.user=user
self.ip=ip
self.password=password
#执行远程指令
def run(self,cmd):
try:
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(self.ip,username=self.user,password=self.password)
for m in cmd:
stdin,stdout,stderr=ssh.exec_command(m)
print stdout.read()
print "Check Status: %s\tOK\n"%(self.ip)
ssh.close()
except:
print "%s\tError\n"%(self.ip)
#创建目录
def mkdir(self):
try:
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(self.ip,username=self.user,password=self.password)
sftp = ssh.open_sftp()
sftp.mkdir("remote_check")
print "Create folder 'remote_check' in remote hosts successfully!\n"
ssh.close()
except:
print "Create folder failure!\n"
#上传本地文件
def upload(self,uSRC,uDST):
env.user=self.user
env.password=self.password
env.host_string=self.ip
put("%s" %(uSRC),"%s" %(uDST))
print "Upload local file : \"%s\" to Host : %s \"%s\"\n" %(uSRC,self.ip.split(':')[0],uDST)
#从远程主机下载文件到本地主机
def download(self,dSRC,dDST):
env.user=self.user
env.password=self.password
env.host_string=self.ip
get("%s" %(dSRC),"%s" %(dDST))
print "Download remote file from : \"%s\" to : %s \"%s\"\n" %(dDST,self.ip.split(':')[0],dSRC)
if __name__ == '__main__':
t=Host("192.168.142.101","root","passwd")
print "Begin......\n"
t.mkdir()
t.upload("/home/test/1.txt","/home/remote_check")
t.download("/home/2.txt","/home/test/2.txt")
cmd = ["whoami","ls","rm -rf /home/1.txt"]
t.run(cmd)