Python模拟SSH登录字符图形菜单

2023-05-16

本文说明如何使用Python模拟SSH登录字符图形菜单(不知道这种菜单叫啥名字,姑且这么叫),并选择相应的菜单项进行操作。
以下图为例,在SSH成功登录后,选择第7行的改密功能项,重复输入密码确认后完成改密,所对应的Python脚本如下。
在这里插入图片描述
在这里插入图片描述

#!/usr/bin/python
# -*- coding: utf-8 -*-

import time
import paramiko

ssh = paramiko.SSHClient()
#这行代码的作用是允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

old_pwd='xxxxxx'
new_pwd='xxxxxx'

ssh.connect(
    hostname = 'xx.xx.xx.xx',
    port = xxx,
    username = "xxxx",
    password = old_pwd
)

# 这段是和命令行交互的写法,和本文无关,但也可以看下
#stdin,stdout,stderr = ssh.exec_command("\nls\n",timeout=60)
#resp=stdout.read()
#print(resp)

channel=ssh.invoke_shell() #交互shell
time.sleep(1)
#channel.send('\x1b') # 这个是发送ESC
#channel.sendall(chr(0x1b)+'OB') # 这个和发送\x1bOB效果一样
channel.sendall('\x1bOB\x1bOB\x1bOB\x1bOB\x1bOB\x1bOB\r') #  发送6个下移箭头,选中第7行的功能项
time.sleep(1)
resp = channel.recv(100000)
if "Please enter new password for" in resp:
	channel.sendall(new_pwd+'\r')
	channel.sendall(new_pwd+'\r')#confirm pwd
	time.sleep(1)
	resp = channel.recv(100000)
	if 'success' in resp:
		print('modify pwd success.')
	ssh.close()
else:
	ssh.close()
	

注:为啥发送下移箭头的键值是\x1bOB呢?其实是参考了这个how-to-send-an-arrow-key-use-paramiko-library-in-python后,再结合在Ubuntu终端里测试了下移箭头对应的可打印字符为^[OB而猜出来的,具体原理没有深究。
在这里插入图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python模拟SSH登录字符图形菜单 的相关文章

随机推荐