Python脚本中如何输入ESC键,实现远程vi编辑器正常模式切换?
解决方案
ESC键对应的ASCII码转义字符为\x1b,你只需要在发送:wq前先发送该字符即可完成vi插入模式到正常模式的切换。同时建议在各命令之间增加短暂延迟,避免命令发送过快导致终端处理异常,另外原代码末尾的ssh_client.close是方法调用,需要补全括号()否则不会执行关闭操作。
修改后的完整代码
import paramiko import time username = input('Username: ') password = input('Password: ') ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(hostname='192.168.30.129', username=username, password=password, look_for_keys=False) remote_connection = ssh_client.invoke_shell() # 创建test文件夹 remote_connection.send("mkdir test\n") time.sleep(0.5) # 打开vi编辑test.txt remote_connection.send("vi test.txt\n") time.sleep(0.5) # 显式进入插入模式,输入内容test remote_connection.send("itest\n") time.sleep(0.5) # 发送ESC键切换到正常模式 remote_connection.send("\x1b") time.sleep(0.5) # 保存退出 remote_connection.send(":wq\n") time.sleep(0.5) output = remote_connection.recv(65535).decode('ascii') print(output) # 补全方法调用括号,正确关闭ssh连接 ssh_client.close()
更稳妥的替代方案
如果只是需要写入文件内容,完全不需要调用vi编辑器,可以直接用shell重定向命令实现,逻辑更简单,没有模式切换的问题:
# 直接写入内容到test.txt,不需要调用vi remote_connection.send("echo 'test' > test/test.txt\n")
内容的提问来源于stack exchange,提问作者Parry Wang
相关产品推荐
相关产品推荐

