Python学习笔记–ssh登录Linux设备(root、非root切换)

  • Post author:
  • Post category:linux


Python学习笔记–ssh登录Linux设备(root、非root切换)



编写成功的代码

# -- coding: UTF-8
__author__ = 'jlr'
import paramiko

class ProcessCheck(object):
    #初始化
    def __init__(self, deviceIP):
        self.deviceIP = deviceIP

    #登录无需跳转用户,如root
    def LoginDevice(self, port, username, password, cmd):
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(self.deviceIP, port, username, password)
        self.stdin, self.stdout, self.stderr = self.ssh.exec_command(cmd)
        return self.stdout.read().decode()

    #登录跳转用户,如zxisec->root
    def logindevice_reinforce(self, port1, username1, password1, root_pwd, cmd2):
        self.ssh2=paramiko.SSHClient()
        self.ssh2.load_system_host_keys()
        self.ssh2.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh2.connect(hostname = self.deviceIP,port=int(port1),username=username1, password=password1)
        if username1 != 'root':
            self.root_login = self.ssh2.invoke_shell()
            self.root_login.send('su - \n')
            buff = ''
            while not buff.endswith('Password: '):
                resp = self.root_login.recv(9999)
                buff +=resp
            self.root_login.send(root_pwd)
            self.root_login.send('\n')
            buff = ''
            while not buff.endswith('# '):
                resp = self.root_login.recv(9999)
                buff +=resp
            self.root_login.send(cmd2)
            self.root_login.send('\n')
            buff = ''
            while not buff.endswith('# '):
                resp = self.root_login.recv(9999)
                buff +=resp
            self.ssh2.close()
            self.result = buff
        else:
            self.stdin, self.stdout, self.stderr = self.ssh2.exec_command(cmd2)
            self.result = self.stdout.read()
            self.ssh2.close()
        return self.result

if __name__ == '__main__':
    pc = ProcessCheck('***')
    m = pc.LoginDevice(***, '***', '***', '***')
    print m
    n = pc.logindevice_reinforce(***, '***', '***', '***', '***')
    print n



中途遇到ssh登录设备失败问题

报错:paramiko.ssh_exception.SSHException: Incompatible ssh peer (no acceptable kex algorithm)

原因:由于ssh 6.7以上屏蔽不安全算法

解决:在/etc/ssh/sshd_config最后加上

KexAlgorithms curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1

重启ssh

service sshd restart



学习笔记

self.stdin, self.stdout, self.stderr = self.ssh2.exec_command(cmd2)

stdin: 标准输入
stdout: 标准输出(正确输出)
stderr: 错误输出
同时只有一个变量有值

stdout.read() 来进行输出,通过stdout.read().decode('utf-8')进行编码转换输出
注意:返回的值是 byte类型,而不是str类型,有需要需要进行转换



版权声明:本文为jinjin_gogo_fighting原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。