Login using Python library paramiko remote device

Foreword

Manually download the installation package paramiko library. Find in PyPi library can be, but is not my computer problem or a network problem, I can not 2.0.0 or later installed, so I myself installed version 1.17.0 paramiko, this version has been tested and can be used

Download and install paramiko

windows manually install, very easy, just find after extracting installation package directory, then you can use the following two commands

python setup.py build
python setup.py install

pip install directly execute the following command, if it is a virtual environment, please switch to the virtual environment after installation

pip install paramiko==1.17.0

Login using equipment paramiko

Login using paramiko library device is extremely simple and strong, under normal circumstances, the use of secureCRT can log in to the device, you will be able to successfully log in using paramiko library. Sample code is as follows:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/2/23 11:05 下午
# @Author : paul
# @Site : 
# @File : test.py


import paramiko

if __name__ == '__main__':
    hostname = '127.0.0.1'  # 主机名
    username = 'root'  # 用户名
    password = '123456'  # 密码

    # ssh login
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=hostname, username=username, password=password, timeout=10)
    # 关闭连接
    ssh.close()
    

This code tested by my own server CentOS6.5, can be used.

After a successful login, of course, hope can enter commands to interact in order to achieve data acquisition system. Here summarizes the three interact.

paramiko and equipment interactively

Enter one command

As shown in the subtitle, for the case of which only need to enter a command, for example, just to get a parameter of the system. At this time, you may be employed in a similar SSHClient exec_command function input command expressed as a string. Sample code is as follows:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/2/23 11:17 下午
# @Author : paul
# @Site : 
# @File : test2.py


import paramiko

if __name__ == '__main__':
    hostname = '127.0.0.1'  # 主机名
    username = 'root'  # 用户名
    password = '123456'  # 密码

    # ssh login
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=hostname, username=username, password=password, timeout=10)

    # 执行命令
    stdin , stdout , stderr = ssh.exec_command(cmd)
    # the stdin, stdout, and stderr of the executing command, as a 3-tuple
    # stdin : 输入内容
    # stdout : 输出内容
    # stderr : 错误信息
    print(stdout.read())
    ssh.close()
    

Of course, there need to be clear, exec_command () method does not mean that can execute only one command, in fact, can execute multiple commands, but this requires multiple commands together into a command && symbols, but this way is only applicable to command prompt the same case:

cmd1 = 'cd /'
cmd2 = 'ls -l'
cmd = cmd1 + "&&" + cmd2

# 执行命令
stdin , stdout , stderr = ssh.exec_command(cmd)

Enter multiple commands

Mode can be achieved in this way a plurality of commands / output file stream analog input through interaction with the system.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/2/23 11:31 下午
# @Author : paul
# @Site : 
# @File : test3.py


import paramiko

if __name__ == '__main__':
    hostname = '127.0.0.1'  # 主机名
    username = 'root'  # 用户名
    password = '123456'  # 密码

    # ssh login
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=hostname, username=username, password=password, timeout=10)

    channel = ssh.invoke_shell()
    stdin = channel.makefile('wb') # 输入流
    stdout = channel.makefile('rb') # 输出流
    
    stdin.write('cd /home\rls\rexit\r') # 输入需要加入回车符号
    print(stdout.read())
    
    ssh.close()
    

Enter the command has stdin.write (command) to complete, should be noted that this interaction interactive way, it will command a one-time finish, including the exit command exit (exit different systems have different commands), each command It indicates the end of a \ R & lt (carriage return).

Multiple input / output interaction

1. class channel in the send (command) function provides a convenient multiple interactions

2. The command input as a string, it is necessary to use "\ r" as the end, but the system is not required as the end command logout of all commands.

3. The interactive commands can be achieved, but requires binding recv_read () method, that is, when allowed to re-read when reading.

The following provides an example of a multi-command interaction. After await_command (channel) waiting function is readable, receive_data (channel) to be read, then read data input command.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/2/23 11:49 下午
# @Author : paul
# @Site : 
# @File : test4.py

import paramiko
import time


def await_command(channel):
    while True:
        if channel.recv_ready():
            return True
        else:
            time.sleep(0.5)
        return False


def receive_data(channel):
    all_data = str()
    while True:
        tmp_data = channel.recv(1024)
        all_data += tmp_data
        # 这里的结束循环的条件可以根据实际情况来设定
        if "#" in all_data:
            break
    return all_data


if __name__ == '__main__':
    hostname = '127.0.0.1'  # 主机名
    username = 'root'  # 用户名
    password = '123456'  # 密码

    try:
        # ssh login
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname=hostname, username=username, password=password, timeout=10)
        # 创建一个面板用来显示交互
        channel = ssh.invoke_shell()

        # 发送命令,接收数据
        channel.send('cd /home\r')
        await_command(channel)
        print(receive_data(channel))

        channel.send('ls -l\r')
        await_command(channel)
        print(receive_data(channel))

        ssh.close()
    except Exception as e:
        raise Exception('connect error')

If you need to read line by line, it can also be applied over makefile, as follows:

def receive_data(channel):
    reader = channel.makefile()
    while True:
        line = reader.readline()
        print(line)
        if '#' in line:
            break
    return line

to sum up

parmiko library is a very powerful library that provides a lot of interaction for us, but in fact we need to choose the appropriate way to interact based on their application, the right is the best.

Guess you like

Origin www.cnblogs.com/oden/p/12355259.html