Python实现的tcp端口检测操作示例
本文实例讲述了Python实现的tcp端口检测操作。分享给大家供大家参考,具体如下:
#coding=utf-8 importsys importsocket importre defcheck_server(address,port): s=socket.socket() print'Attemptingtoconnectto%sonport%s'%(address,port) try: s.connect((address,port)) print'Connectedto%sonport%s'%(address,port) returnTrue exceptsocket.errorase: print'Connectionto%sonport%sfailed:%s'%(address,port,e) returnFalse if__name__=='__main__': fromargparseimportArgumentParser parser=ArgumentParser(description=u'TCP端口检测') parser.add_argument( '-a', '--address', dest='address', default='localhost', help='addressfortheserver') parser.add_argument( '-p', '--port', dest="port", default=80, type=int, help='portfortheserver') args=parser.parse_args() check=check_server(args.address,args.port) print'check_serverreturned%s'%check sys.exit(notcheck)
测试结果:
[hupeng@hupeng-vmPython]$pythoncheck_server.py&&echo"SUCCESS"
Attemptingtoconnecttolocalhostonport80
Connectedtolocalhostonport80
check_serverreturnedTrue
SUCCESS
[hupeng@hupeng-vmPython]$pythoncheck_server.py-p81&&echo"Failure"
Attemptingtoconnecttolocalhostonport81
Connectiontolocalhostonport81failed:[Errno111]Connectionrefused
check_serverreturnedFalse
[hupeng@hupeng-vmPython]$pythoncheck_server.py-p81||echo"Failure"
Attemptingtoconnecttolocalhostonport81
Connectiontolocalhostonport81failed:[Errno111]Connectionrefused
check_serverreturnedFalse
Failure
附:
shell中&&和||的使用方法
命令的返回结果:真(返回0),假(返回非0)
command1 &&command2:command1返回真时,command2才会被执行
command1 ||command2:command1返回真时,command2就不会被执行
更多关于Python相关内容可查看本站专题:《PythonSocket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。