Python远程执行Shell命令

修改代码RemoteShell.app部分,执行对应的Shell命令。
#!/usr/bin/env python3
# _*_ coding:utf8 _*_
from paramiko import SSHClient,AutoAddPolicy  #pip3 install paramiko -i https://pypi.tuna.tsinghua.edu.cn/simple/

class RemoteShell():
    def __init__(self,host,port,user,pswd):
        self.host,self.port = host,port
        self.user,self.pswd = user,pswd
        self.ssh_client = None

    #执行shell
    def remote_shell(self,shell,title=""):   #命令,标题
        stdin, stdout, stderr = self.ssh_client.exec_command(shell)
        for i in stdout.readlines():
            print("%s\t%s\t%s"%(self.host,title,str(i).strip()))

    def app(self):
        self.remote_shell("uptime", '运行时长 ')
        self.remote_shell('cat /etc/redhat-release ',"系统版本")
        self.remote_shell("crontab -l","定时任务")

    def run(self):
        try:
            #创建连接
            self.ssh_client = SSHClient()
            key = AutoAddPolicy()
            self.ssh_client.set_missing_host_key_policy(key)
            self.ssh_client.connect(self.host, self.port, self.user, self.pswd, timeout=3)
            
            self.app()
            
            self.ssh_client.close()
        except Exception as e:
            print(self.host,str(e))


RemoteShell("192.168.1.105",22,"root","123456").run()

 


class RemoteShell():
    def __init__(self, host, port, user, pswd,shells,error_break=True):
        self.host, self.port = host, port
        self.user, self.pswd = user, pswd
        self.shells = shells
        self.error_break = error_break
        self.ssh_client = None
        self.msgs = []

    def execute(self, shell):
        stdin, stdout, stderr = self.ssh_client.exec_command(shell)
        return {"shell":shell,"result":list(stdout),"error":" ; ".join(list(stderr))}

    def run(self):
        self.ssh_client = SSHClient()
        key = AutoAddPolicy()
        self.ssh_client.set_missing_host_key_policy(key)
        self.ssh_client.connect(self.host, int(self.port), self.user, self.pswd, timeout=3)
        for shell in self.shells:
            msg = self.execute(shell)
            self.msgs.append(msg)
            if self.error_break and msg.get("error",None):
                break
        self.ssh_client.close()
        return self.msgs

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值