python远程管理编程中如何处理Fn(功能)键
我之前管理过一款通讯设备,是需要登录远程管理客户端后才能进行操作的。这个设备的远程管理软件的功能挺多,但是主要的设备管理操作还是在一个单调的字符界面下完成的,后来经其他工程师提醒,我才意识到此时该软件就相当于一个“封装”后Telnet客户端(终端)。
由于这个“带有迷惑性”的客户端,再加上大家的操作习惯,平时大家的操作都是手工完成的,即使每天都有重复的工作,即使每次切换都是相同的操作步骤。手工操作不仅耗时长,而且易出错,切换完以后还要逐一核对切换后的信息,每次这一套流程做完,差不多十来分钟就过去了!
接触python以后,我就希望能通过python程序来“自动化/批量”处理这样的常规操作,而且不仅可以实现python程序“自动化”切换,也能对平时的设置进行检查。找到一款可以实现telnet功能的python模块并不难,连接设备并且检查系统设置也没有遇到多大问题,但是在执行设备“切换”操作步骤的时候,我遇到了“拦路虎”——客户端操作需要使用F1等多个功能键,才能修改初始数据并提交给设备。
我试着通过搜索引擎搜索,试着检索ascii码表,都没有找到有用的信息,就在“迷茫无措”时,偏偏让我从Putty客户端的帮助文件中找到了相关的信息:
- In the default mode, labelled ESC [n~, the function keys generate sequences like ESC [11~, ESC [12~ and so on. This matches the general behaviour of Digital's terminals.
- In Linux mode, F6 to F12 behave just like the default mode, but F1 to F5 generate ESC [[A through to ESC [[E. This mimics the Linux virtual console.
- In Xterm R6 mode, F5 to F12 behave like the default mode, but F1 to F4 generate ESC OP through to ESC OS, which are the sequences produced by the top row of the keypad on Digital's terminals.
- In VT400 mode, all the function keys behave like the default mode, but the actual top row of the numeric keypad generates ESC OP through to ESC OS.
- In VT100+ mode, the function keys generate ESC OP through to ESC O[
- In SCO mode, the function keys F1 to F12 generate ESC [M through to ESC [X. Together with shift, they generate ESC [Y through to ESC [j. With control they generate ESC [k through to ESC [v, and with shift and control together they generate ESC [w through to ESC [{.
PuTTY responds to function key presses by sending a sequence of control characters to the server.
……
The simplest way to investigate this is to find some other terminal environment, in which that function key does work; and then investigate what sequence the function key is sending in that situation. One reasonably easy way to do this on a Unix system is to type the command cat, and then press the function key. This is likely to produce output of the form ^[[11~. You can also do this in PuTTY, to find out what sequence the function key is producing in that.
也就是说,在python程序中需要通过发送一段特定的字符串,比如ESC [11~……等来实现功能键的录入,具体的字符串需要与python程序模拟的telnet终端的类型(VT100等)相匹配。我们可以在Unix/Linux终端中,执行命令cat,在命令中按下功能键Fn,实际输出结果就刚提交的字符串组合,比如ESC键显示为“^[”,F6显示“^[[17~”……,当然我们更可以在设备终端中执行以上的操作,查看功能键对应的字符串组合。最后大家还是要通过在python程序中的测试,来验证获取的Fn功能键录入字符串是否正确、有效!
好了,这就是我曾经遇到的一个“拦路虎”,“突破”以后分析给大家,希望能对大家有所帮助。