短选项名后的冒号:表示该选项必须有附加的参数
长选项名后的等号=表示该选项必须有附加的参数
返回 opts 和 args:
cmd命令行输入如下:
python example.py -i 192.168.1.110 -p 80 -l --help 123
python程序如下:
import sys
import getopt
opts,args=getopt.getopt(sys.argv[1:],"li:p:",["help"])
print(opts);
print(args)
sys.argv[1:]获得就是从第二个参数开始一直到后面的参数
li:p: 表示短选项,l后面不带参数,i后面需要跟上参数,同理
[“help”]表示参数行得是–help
返回的opts就是((‘-i’,’192.168.1.110’),(‘-p’,’80’),(‘-l’,”),(‘–help’,”))参数选项及其value的元组
args 是一个除去有用参数外其他的命令行输入 (‘123’)
用到的socket函数 | 描述 |
---|---|
socket.gethostbyname(hostname) | 将主机名转换为ip地址 |
socket.gethostbyaddr(ip_address) | 通过ip地址,返回包括主机名的三元组:(hostname, aliaslist, ipaddrlist) |
==完整代码==
#coding=UTF-8
import getopt
import socket
import sys
def connScan(target_host,target_port):
try:
conn=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
conn.connect((target_host,target_port))
conn.send('test\r\n')#通过发送数据捕获运行在目标主机端口的应用程序的一些信息
results=conn.recv(1024)
print('[+]{0}/tcp open'.format(target_port))
print('[+] {0}'.format(str(results)))
conn.close()
except:
print('[-]{0}/tcp closed'.format(target_port))
def portScan(target_host,target_ports):
try:
target_ip=socket.gethostbyname(target_host)
except:
print("[-]Cannot resolve {0}:Unknow host".format(target_host))
return
try:
target_name=socket.gethostbyaddr(target_ip)
print("\n[+] scan result for:{0}".format(target_name[0]))
except:
print("\n[+] scan result for:{0}".format(target_ip))
socket.setdefaulttimeout(1)
for target_port in target_ports:
print("Scanning port"+str(target_port))
connScan(target_host,int(target_port))
def usage():
print('---------------------------------------------')
print()
print()
print("usage:scan_port.py -t target_host -p ports")
print("scan_port.py -t 192.168.1.1 -p 21,23,445,3389")
print()
print()
print('---------------------------------------------')
sys.exit(0)
def main():
try:
opts,args=getopt.getopt(sys.argv[1:],"ht:p:",["help","target","ports"])
except getopt.GetoptError as err:
print(str(err))
usage()
for o,a in opts:
if o in ("-h","--help"):
usage()
elif o in ("-t","--target"):
target_ip=a
elif o in ("-p","--ports"):
ports=a.split(',')
else:
assert False,'Unhandled option'
portScan(target_ip,ports)
if __name__=='__main__':
main()