python远程执行linux命令256_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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值