current position:Home>python---SSH connection to linux service

python---SSH connection to linux service

2022-08-06 07:36:25night breeze


一、paramiko库使用

Python第三方库paramikois for remote controllinux主机的,进行ssh连接时,需要用到Python的paramiko,Dependent libraries must be installed first

安装命令:

pip install paramiko

导入包:

import paramiko

连接方法:

paramiko.SSHClient()

执行方法:

exec_command()

断开连接:

close()

二、使用实例

代码如下(示例):

import paramiko

class SSHLinux():
    def __init__(self, hostname, port, username, password):
     	# 创建sshClient实例对象
        ssh = paramiko.SSHClient()
        # Set to trust the remote machine,允许访问
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh = ssh
        self.ssh.connect(hostname,port=port,username=username, password=password)

    def use_command(self,cmd):
        try:
            """ stdin 标准格式的输入,是一个写权限的文件对象 stdout 标准格式的输出,是一个读权限的文件对象 stderr 标准格式的错误,是一个写权限的文件对象” Executing the command returns three objects,调用一次exec_commandThe method is equivalent to reopening it oncelinux终端 """
			
            stdin,stdout,stderr = self.ssh.exec_command(cmd)
            res = stdout.read().decode()
            return res
        except Exception as e:
            print(e)
        finally:
            self.ssh.close()

hostname = "192.168.90.X"
port = 22
username = "root"
password = ""
ssh = SSHLinux()(hostname, port=port, username=username, password=password)
ssh.use_command("ll")

copyright notice
author[night breeze],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/218/202208060720531485.html

Random recommended