sqlalchemy 数据库操作

sqlAlchemy是python中最著名的ORM(Object Relationship Mapping)框架。

ORM 从开发角度说,就是采用面向对象的方式来直接操作数据库,方便的很,不用写那么多数据库查询语句。

这里记录一下增删查改命令。

安装方法:

1
2
python -m pip install sqlalchemy
python -m pip install pymysql

参考代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from sqlalchemy import Column,String,Integer,create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

engine = create_engine('mysql+pymysql://root:root@localhost:3306/info')

DBSession = sessionmaker(bind=engine)


class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String)
passwd = Column(String)

# 增加数据
try:
db = DBSession()
db.add(User(name="Hacker1",passwd="1234561"))# 增
db.commit()
db.close()
except :
pass

## 查询数据
try:
db = DBSession()
# 查所有
results = db.query(User).all()
for r in results:
print(r.name)
#条件过滤
result = db.query(User).filter_by(id = 4).first()
print(result.name)
# 条件大于
results = db.query(User).filter(User.id > 5).all()
for r in results:
print(r.name)
db.close()
except :
pass

## 修改数据
try:
db = DBSession()
result = db.query(User).filter_by(id = 7).first()
result.name = "what"
db.commit()
db.close()
except :
pass

## 删
try:
db = DBSession()
result = db.query(User).filter_by(id = 9).first()
db.delete()
db.commit()
db.close()
except Exception as e :
print(e)
pass

利用python连接并控制SSH

使用pexpect来连接ssh

(该工具只能在linux下使用)

python连接ssh并且执行命令,显示输出结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/usr/bin/python
import pexpect
PROMPT = ['# ','>>> ','> ','\$ ']
def send_command(child,cmd):
child.sendline(cmd)
child.expect(PROMPT)
print child.before

def connect(user,host,password):
ssh_newkey = 'Are you sure you want to continue connecting (yes/no)?'
connStr = 'ssh ' + user + '@' + host
child = pexpect.spawn(connStr)
ret = child.expect([pexpect.TIMEOUT,ssh_newkey,'[P|p]assword: '])
if ret == 0:
print '[-] Error Connecting'
return
if ret ==1:
print "send yes to server!\n"
child.sendline('yes')
ret = child.expect([pexpect.TIMEOUT,'[P|p]assword: '])
if ret == 0:
print '[-] Error Connecting'
return
child.sendline(password)
child.expect(PROMPT)
return child
ss = connect("root","heiyiren.top","heiyiren312429020!@#")
send_command(ss,'cat /etc/shadow | grep root')

python之端口扫描

使用python脚本进行tcp全连接测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from socket import *
from threading import Thread
import optparse

def connPort(ipAddr,port):
setdefaulttimeout(1)
try:
conn = socket(AF_INET,SOCK_STREAM)
conn.connect((ipAddr,port))
conn.send(b"python\r\n")
print("[+] %d/tcp open"%port)
results = conn.recv(100)

print("[+] %s"%str(results,encoding="utf-8"))
except Exception as e:
#print(e)
pass

if __name__ == "__main__":
parser = optparse.OptionParser("python portscan.py -H <host ip addr> -p <port>")
parser.add_option("-H",dest='hAddr',type='string',help='specify ip addr')
parser.add_option("-p",dest='port',type='string',help='specify port')
(options,args) = parser.parse_args()
if options.hAddr==None or options.port==None:
print(parser.usage)
else:
ports = str(options.port).split(",")
for i in ports:
t = Thread(target=connPort,args=(options.hAddr,int(i)))
t.start()

python破解zip密码

今天写了个小脚本,用于暴力破解zip密码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import zipfile
from threading import Thread
import optparse

def testZipPasswd(zfile,passWord):
try:
zfile.extractall(pwd=passWord)
print("[+] Found Password: "+str(passWord,encoding="utf-8"))
except Exception as e:
#print(e)
pass
def decodeZipPasswd(zfile,passfile):
with open(passfile) as f:
zfile = zipfile.ZipFile(zfile)
for i in f.readlines():
i = i.replace("\n","")
t = Thread(target=testZipPasswd,args=(zfile, i.encode(encoding="utf-8")))
t.start()
if __name__ == "__main__":
parser = optparse.OptionParser("python zip.py -f <zipfile> -p <passfile>")
parser.add_option("-f",dest='zname',type='string',help='specify zip file')
parser.add_option("-p",dest='passwd',type='string',help='specify password file')
(options,args) = parser.parse_args()
if options.zname ==None or options.passwd==None:
print(parser.usage)
exit(0)
else:
decodeZipPasswd(options.zname,options.passwd)

python获取网卡信息

Python获取本机IP地址的一般方法为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import socket

IP = socket.gethostbyname(socket.gethostname())
  通过gethostname获取主机名,再用gethostbyname将主机名转换为IP地址。

  那么,问题来了。如果主机有多个网卡/IP,怎样获取某个指定的IP地址呢?

  一个方法是通过socket.gethostbyname_ex获取主机IP地址列表,然后遍历列表取得自己需要的IP。

import socket

#多网卡情况下,根据前缀获取IP(Windows 下适用)
def GetLocalIPByPrefix(prefix):
localIP = ''
for ip in socket.gethostbyname_ex(socket.gethostname())[2]:
if ip.startswith(prefix):
localIP = ip

return localIP


print(GetLocalIPByPrefix('192.168'))

更简单的方法(不用修改代码,还是用socket.gethostname函数),是通过配置hosts文件改变IP优先级。

上面的方法只支持IPv4,如果要获取IPv6信息,参考socket.getaddrinfo。

1、用系统库获取单机 mac 地址。

import uuid

针对单网卡

1
2
3
4
def GetMAC():
addr = hex(uuid.getnode())[2:].upper()

return '-'.join(addr[i:i+2] for i in range(0, len(addr), 2))

2、用第三方库 psutil 打印网络适配器信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import psutil

# 打印多网卡 mac 和 ip 信息
def PrintNetIfAddr():
dic = psutil.net_if_addrs()
for adapter in dic:
snicList = dic[adapter]
mac = '无 mac 地址'
ipv4 = '无 ipv4 地址'
ipv6 = '无 ipv6 地址'
for snic in snicList:
if snic.family.name in {'AF_LINK', 'AF_PACKET'}:
mac = snic.address
elif snic.family.name == 'AF_INET':
ipv4 = snic.address
elif snic.family.name == 'AF_INET6':
ipv6 = snic.address
print('%s, %s, %s, %s' % (adapter, mac, ipv4, ipv6))

跨平台的根据前缀获取 ip 的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import psutil

# 多网卡情况下,根据前缀获取IP
# 测试可用:Windows、Linux,Python 3.6.x,psutil 5.4.x
# ipv4/ipv6 地址均适用
# 注意如果有多个相同前缀的 ip,只随机返回一个
def GetLocalIPByPrefix(prefix):
localIP = ''
dic = psutil.net_if_addrs()
for adapter in dic:
snicList = dic[adapter]
for snic in snicList:
if not snic.family.name.startswith('AF_INET'):
continue
ip = snic.address
if ip.startswith(prefix):
localIP = ip

return localIP


print(GetLocalIPByPrefix('192.168'))