python的paramiko源码修改了一下,写了个操作命令的日志审计,但是记录的日志中也将backspace删除键记录成^H这个了,于是改了一下代码,用字符串的特性。
字符串具有列表的特性
>>> a="hello world" >>> a[:-1] 'hello worl'
转义符
转义字符 (在行尾时) 续行符 \ 反斜杠符号 ' 单引号 " 双引号 a 响铃 退格(Backspace) e 转义 000 空 换行 v 纵向制表符 横向制表符 回车 f 换页 oyy 八进制数yy代表的字符,例如:o12代表换行 xyy 十进制数yy代表的字符,例如:x0a代表换行 other 其它的字符以普通格式输出
代码部分
if sys.stdin in r: x = sys.stdin.read(1) if x == '': cmd=cmd[:-1] else: cmd+=x #records.append(x) if x == ' ': #print "your input is:",cmd log_line = "-login_user:%s |host_addr:%s |%s|HISTORY_CMD: %s " % (username,hostname,time.strftime("%Y_%m_%d %H:%M:%S"),cmd) cmd = '' log_file.write(log_line)
操作演示 123456789 删除3 6 9键入三个键 如下标红
root@python:~/baolei# sh remote.sh ######################################################## 1: [haproxy] w1.dev.haproxy.org 192.168.0.105 ######################################################## before choose items will be sleep a monent Please choose ip of top:1 Please input your username:root root 192.168.0.105 192.168.0.105 root username:root *** WARNING: Unknown host key! Auth by (p)assword, (r)sa key, or (d)ss key? [p] Password for root@192.168.0.105: *** Here we go! Last login: Thu Feb 25 15:44:25 2016 from 192.168.0.106 /data/x/tools/team/env/alias.env fatal: Not a git repository (or any of the parent directories): .git /data/x/tools/team/env/git-completion.env ansible-direc:~ # 124578 -bash: 124578: command not found ansible-direc:~ # exit logout *** EOF root@python:~/baolei# vim /tmp/root/192.168.0.105_audit_log_2016_02_27.log root@python:~/baolei# vim /tmp/root/192.168.0.105_audit_log_2016_02_27.log root@python:~/baolei# vim /tmp/liujianzuo/192.168.0.102_audit_log_2016_02_27.log root@python:~/baolei# vim interactive.py root@python:~/baolei# tail /tmp/root/192.168.0.105_audit_log_2016_02_27.log login_user:root |host_addr:192.168.0.105 |2016_02_27 13:24:51|HISTORY_CMD: ls login_user:root |host_addr:192.168.0.105 |2016_02_27 13:24:53|HISTORY_CMD: exit login_user:root |host_addr:192.168.0.105 |2016_02_27 13:40:27|HISTORY_CMD: ls login_user:root |host_addr:192.168.0.105 |2016_02_27 13:40:29|HISTORY_CMD: lll login_user:root |host_addr:192.168.0.105 |2016_02_27 13:40:38|HISTORY_CMD: sd login_user:root |host_addr:192.168.0.105 |2016_02_27 13:40:44|HISTORY_CMD: exit login_user:root |host_addr:192.168.0.105 |2016_02_27 13:57:16|HISTORY_CMD: 9 login_user:root |host_addr:192.168.0.105 |2016_02_27 13:57:19|HISTORY_CMD: exit login_user:root |host_addr:192.168.0.105 |2016_02_27 14:02:53|HISTORY_CMD: 124578 login_user:root |host_addr:192.168.0.105 |2016_02_27 14:02:54|HISTORY_CMD: exit
shell 变量传入python脚本,修改后的源码脚本就不粘贴了。
root@python:~/baolei# cat remote.sh #!/bin/sh #created by liujianzuo list(){ #cd /home/liujianzuo/server/scripts echo "