(入门)几个关于python的简单远程执行命令的代码操作

我们在学习python的同时,有时会需要在远程的机器上执行一个命令,并获得其返回结果。对于这种情况,python 其实是可以很容易实现的。我们今天就通过简单的实例代码,来介绍下python的 远程执行命令的相关知识。点击领取更多的关于python免费学习知识和技巧。

1.简单版

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

# coding: utf-8

import paramiko

import re

from time import sleep

def ssh():

    ssh = paramiko.SSHClient()

    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())    #指定当对方主机没有本机公钥的情况时应该怎么办,AutoAddPolicy表示自动在对方主机保存下本机的秘钥

    ssh.connect('172.16.1.5',22,'linyouyi','123456')    #SSH端口默认22,可改

    stdin,stdout,stderr = ssh.exec_command("df -hl")    #这三个得到的都是类文件对象

    outmsg,errmsg = stdout.read(),stderr.read()    #读一次之后,stdout和stderr里就没有内容了,所以一定要用变量把它们带的信息给保存下来,否则read一次之后就没有了

    #outmsg = str(outmsg)

    #print(outmsg.replace("\\n","\\r\\n"))

    print(outmsg.decode())

    print(errmsg)

    if errmsg == "":

        print(outmsg)

    ssh.close()

if __name__ == '__main__':

    ssh()

2.封装版

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

# coding: utf-8

import paramiko

import re

from time import sleep

# 定义一个类,表示一台远端linux主机

class Linux(object):

    # 通过IP, 用户名,密码,超时时间初始化一个远程Linux主机

    def __init__(self, ip, username, password, timeout=30):

        self.ip = ip

        self.username = username

        self.password = password

        self.timeout = timeout

        # transport和chanel

        self.t = ''

        self.chan = ''

        # 链接失败的重试次数

        self.try_times = 3

    # 调用该方法连接远程主机

    def connect(self):

        while True:

            # 连接过程中可能会抛出异常,比如网络不通、链接超时

            try:

                self.t = paramiko.Transport(sock=(self.ip, 22))

                self.t.connect(username=self.username, password=self.password)

                self.chan = self.t.open_session()

                self.chan.settimeout(self.timeout)

                self.chan.get_pty()

                self.chan.invoke_shell()

                # 如果没有抛出异常说明连接成功,直接返回

                print(u'连接%s成功' % self.ip)

                # 接收到的网络数据解码为str

                print(self.chan.recv(65535).decode('utf-8'))

                return

            # 这里不对可能的异常如socket.error, socket.timeout细化,直接一网打尽

            except Exception as e1:

                if self.try_times != 0:

                    print(u'连接%s失败,进行重试' %self.ip)

                    self.try_times -= 1

                else:

                    print(u'重试3次失败,结束程序')

                    exit(1)

    # 断开连接

    def close(self):

        self.chan.close()

        self.t.close()

    # 发送要执行的命令

    def send(self, cmd):

        cmd += '\r'

        # 通过命令执行提示符来判断命令是否执行完成

        p = re.compile(r']$')

        result = ''

        # 发送要执行的命令

        self.chan.send(cmd)

        # 回显很长的命令可能执行较久,通过循环分批次取回回显

            sleep(2)

            ret = self.chan.recv(65535)

            ret = ret.decode('utf-8')

            result += ret

            if p.search(ret):

                print(result)

                return(result)

                 

if __name__ == '__main__':

    host = Linux('172.16.1.5', 'linyouyi', '123456')

    host.connect()

    host.send('ll')

    host.close() 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值