Home >Backend Development >Python Tutorial >Use paramiko interactive applet

Use paramiko interactive applet

高洛峰
高洛峰Original
2016-11-21 10:40:551523browse

小程序如下:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import paramiko
RED_COLOR='\033[1;31;48m'  #红 ,配置终端输出的颜色
BLUE_COLOR='\033[1;34;48m'  #蓝 ,配置终端输出的颜色
RES='\033[0m'
def SSH_Pkey(Host,UserName,Pkey,Port=22):
    #基于用户名密钥连接并执行命令
    try:
        private_key = paramiko.RSAKey.from_private_key_file(Pkey)
        # 创建SSH对象
        SSH = paramiko.SSHClient()
        # 允许连接不在know_hosts文件中的主机
        SSH.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # 连接服务器
        SSH.connect(hostname=Host, port=Port, username=UserName,key_filename=Pkey)
        # 执行命令
        print ("%s成功登录到服务器%s,请输入操作命令!%s"%(RED_COLOR,Host,RES) )
        while True:
            CMD=input('%s请输入输入操作命令:%s'%(BLUE_COLOR,RES))
            if CMD=='exit':
                print ("%s执行%s命令退出!%s" %(RED_COLOR,CMD,RES))
                # 关闭连接
                SSH.close()
                break
            else:
                stdin, stdout, stderr = SSH.exec_command(CMD)
                print ("%s执行命令%s返回结果:%s"%(RED_COLOR,CMD,RES))
                for i in stdout.read().splitlines():
                    print (i.decode('utf-8'))
    except :
        print ("%sSSH远程登录失败,退出程序!\n" %(RED_COLOR,RES ))
 
if __name__ == '__main__':
    Host='59.1.1.1'
    UserName='root'
    SSH_Key=r'D:\Identity2048'
    Port = 6382
    SSH_Pkey(Host=Host,UserName=UserName,Pkey=SSH_Key,Port=Port)

效果图如下:

Use paramiko interactive applet

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Python input usesNext article:Python input uses