以下代码在python 2.6.6下测试通过
添加帐号并修改密码:
(注:linux的expect命令也可以完成,交互式自动输入的功能)
#!/usr/bin/env pythonaccount = 'sl_t1'passwd='a1p2p3l4e5'cmd_useradd = 'useradd %s' % (account) #添加用户命令,根据需要自行修改 import subprocess as sp def useradd(): cmd = 'export LC_ALL=en_US && %s' % (cmd_useradd) f=open('/dev/null', 'w') ret = sp.call(cmd, shell=True, stdout=f, stderr=f) f.close() return ret def passwd(): cmd = 'export LC_ALL=en_US && passwd %s' % (account) f=open('/dev/null', 'w') p = sp.Popen(cmd, shell=True, stdin=sp.PIPE, stdout=f, stderr=f) p.stdin.write("%s\n" % (passwd)) p.stdin.write("%s\n" % (passwd)) f.close() return p.wait() def pymain(): #print 'useradd: ', useradd() #print 'passwd: ', passwd() ret = useradd() if not 0==ret: print 'useradd ',ret return ret = passwd() if not 0==ret: print 'passwd ',ret return print 'done' #如果工作正常返回done,否则返回失败的步骤及错误码 if __name__=='__main__': pymain()
端口连接测试
#!/usr/bin/env pythonimport socketimport sysaddress=('127.0.0.1',22)if len(sys.argv)>1: address=(sys.argv[1], int(sys.argv[2]))else : print 'format: %s' % sys.argv[0]s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)print "connect %s:%d %s" % (address[0],address[1],s.connect_ex(address)==0)s.close()
端口扫描
#!/usr/bin/env pythonimport socketimport sysdef scanPort(ips,ports,out=None): ret = [] socket.setdefaulttimeout(0.5) for ip in ips: for port in ports: try: c = socket.socket(socket.AF_INET,socket.SOCK_STREAM) cr = 0==c.connect_ex((ip,port)) if not out is None: print >>out,'%s:%d %s' % (ip,port,cr) ret.append('%s:%d %s' % (ip,port,cr)) except Exception as e: if not out is None: print >>out,'%s:%d %s' % (ip,port,e) ret.append('%s:%d %s' % (ip,port,e)) finally: if not c is None: c.close() return ret def help(): print '%s' % (sys.argv[0]) print "eg: %s 192.168.2.100 22" % (sys.argv[0]) print "eg: %s 192.168.2.100,192.168.2.200 22,23,30-40,80" % (sys.argv[0])def pymain(): if not len(sys.argv)==3: help() return else: ips = [] ports = [] for ip in sys.argv[1].split(','): ips.append(ip) for port in sys.argv[2].split(','): if not -1==port.find('-'): i = int(port.split('-')[0]) end = int(port.split('-')[1]) while i<=end: ports.append(i) i+=1 else: ports.append(int(port)) if 0==len(ips) or 0==len(ports): help() else: scanPort(ips,ports,sys.stdout) if __name__=='__main__': pymain()