一、ORM
连表
一对多
1、创建表,主动指定外键约束
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index,Table from sqlalchemy.orm import sessionmaker, relationship engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/s13", max_overflow=5) Base = declarative_base() # 单表 class Test(Base): __tablename__ = 'test' nid = Column(Integer, primary_key=True,autoincrement=True) name = Column(String(32)) # 一对多 class Group(Base): __tablename__ = 'group' nid = Column(Integer, primary_key=True,autoincrement=True) caption = Column(String(32)) class User(Base): __tablename__ = 'user' nid = Column(Integer, primary_key=True,autoincrement=True) username = Column(String(32)) group_id = Column(Integer, ForeignKey('group.nid')) group = relationship("Group", backref='uuu') def __repr__(self): temp = "%s - %s: %s" %(self.nid, self.username, self.group_id) return temp
2、操作
类:repr
class User(Base): __tablename__ = 'user' nid = Column(Integer, primary_key=True,autoincrement=True) username = Column(String(32)) group_id = Column(Integer, ForeignKey('group.nid')) group = relationship("Group", backref='uuu') def __repr__(self): temp = "%s - %s: %s" %(self.nid, self.username, self.group_id) return temp
单表
Session = sessionmaker(bind=engine) session = Session() session.add_all([ Host(hostname='c1',port='22',ip='1.1.1.1'), Host(hostname='c2',port='22',ip='1.1.1.2'), Host(hostname='c3',port='22',ip='1.1.1.3'), Host(hostname='c4',port='22',ip='1.1.1.4'), Host(hostname='c5',port='22',ip='1.1.1.5'), ]) session.commit()
连表
session.query(表1).join(表2).all()
ret = session.query(User.username).all() print(ret) sql = session.query(User,Group).join(Group, isouter=True) print(sql) ret = session.query(User,Group).join(Group, isouter=True).all() print(ret) sql = session.query(User.username,Group.caption).join(Group, isouter=True) print(sql) ret = session.query(User.username,Group.caption).join(Group, isouter=True).all() print(ret) select * from user left join group on user.group_id = group.nid
多对多
1、创建表,额外的关系表
2、filter()
==
in_( 都可以是另外一个查询)
3、relationship
A
AB ==> fk, 关系
B
class Test(Base): __tablename__ = "test" nid = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(32)) class Group(Base): __tablename__ = "group" nid = Column(Integer, primary_key=True, autoincrement=True) caption = Column(String(32)) class User(Base): __tablename__ = "user" nid = Column(Integer,primary_key=True,autoincrement=True) username = Column(String(32)) group_id = Column(Integer, ForeignKey("group.nid")) group = relationship("Group", backref="uuu") #查询时使用,与外键一起使用 “Group” 类名(表),uuu是反向 def __repr__(self): temp = "%s - %s: %s" %(self.nid, self.username, self.group_id) return temp Session = sessionmaker(bind=engine) session = Session() #正向查询 ret = session.query(User).all() for obj in ret: print(obj.nid, obj.username, obj.group_id, obj.group.nid,obj.group.caption) #反向查询 obj = session.query(Group).filter(Group.caption == "DBA").first() print(obj.nid) print(obj.caption) print(obj.uuu)
4、简单
A 关系(B,ABTable对象)
AB ==>fk,
B
操作时,简单
class HostToHostUser(Base): __tablename__ = 'host_to_host_user' nid = Column(Integer, primary_key=True,autoincrement=True) host_id = Column(Integer,ForeignKey('host.nid')) host_user_id = Column(Integer,ForeignKey('host_user.nid')) # host = relationship("Host", backref='h') # host_user = relationship("HostUser", backref='u') def __repr__(self): temp = "%s - %s: %s" %(self.nid, self.username, self.group_id) return temp class Host(Base): __tablename__ = 'host' nid = Column(Integer, primary_key=True,autoincrement=True) hostname = Column(String(32)) port = Column(String(32)) ip = Column(String(32)) host_user = relationship("HostUser", secondary=HostToHostUser.__table__,backref='h') class HostUser(Base): __tablename__ = 'host_user' nid = Column(Integer, primary_key=True,autoincrement=True) username = Column(String(32))
class Host(Base): __tablename__ = 'host' nid = Column(Integer, primary_key=True,autoincrement=True) hostname = Column(String(32)) port = Column(String(32)) ip = Column(String(32)) host_user = relationship("HostUser", secondary=lambda :HostToHostUser.__table__,backref='h') class HostUser(Base): __tablename__ = 'host_user' nid = Column(Integer, primary_key=True,autoincrement=True) username = Column(String(32)) class HostToHostUser(Base): __tablename__ = 'host_to_host_user' nid = Column(Integer, primary_key=True,autoincrement=True) host_id = Column(Integer,ForeignKey('host.nid')) host_user_id = Column(Integer,ForeignKey('host_user.nid')) # host = relationship("Host", backref='h') # host_user = relationship("HostUser", backref='u') def __repr__(self): temp = "%s - %s: %s" %(self.nid, self.username, self.group_id) return temp
Table对象:
A 关系(B,Table对象方法)
Table对象方法 AB ==>fk,
B
操作时,简单
A 关系(B,AB.__table__)
AB ==>fk,
B
操作时,简单
sqlachemy回顾:
1、创建表
2、操作表
#单表
#连表
.join
关系:
一对多
fk,关系
多对多,
多一张表 fk,fk
1、 关系表:关系
2、A:关系,(B,AB)
二、paramiko模块
SSHClient
用户名、密码:
SSHClient,Tranport
SFTPClient:
用户名、密码
Tranport
需求:
命令、上传文件、命令
import paramiko
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Author: Aaron Shen # Author:Alex Li import paramiko import uuid class SSHConnection(object): def __init__(self, host='192.168.11.90', port=22, username='root',pwd='123'): self.host = host self.port = port self.username = username self.pwd = pwd self.__k = None def run(self): self.connect() pass self.close() def connect(self): transport = paramiko.Transport((self.host,self.port)) transport.connect(username=self.username,password=self.pwd) self.__transport = transport def close(self): self.__transport.close() def cmd(self, command): ssh = paramiko.SSHClient() ssh._transport = self.__transport # 执行命令 stdin, stdout, stderr = ssh.exec_command(command) # 获取命令结果 result = stdout.read() return result def upload(self,local_path, target_path): # 连接,上传 sftp = paramiko.SFTPClient.from_transport(self.__transport) # 将location.py 上传至服务器 /tmp/test.py sftp.put(local_path, target_path) def download(self, remove_path, local_path=r"C:download est"): sftp = paramiko.SFTPClient.from_transport(self.__transport) sftp.get(remove_path, local_path) ssh = SSHConnection() ssh.connect() # r1 = ssh.cmd('find / -name "*.mp*"') # print(r1) # ssh.upload('t2.py', "/root/t2.py") ssh.upload("C:迅雷下载【6v电影www.dy131.com】楚门的世界BD中英双字1280高清.rmvb",'/home/lmd/12.mp4') ssh.close()
Tranport
Tranport关闭
# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='c1.salt.com', port=22, username='wupeiqi', password='123')
# 执行命令
stdin, stdout, stderr = ssh.exec_command('ls')
# 获取命令结果
result = stdout.read()
# 关闭连接
ssh.close()
import paramiko
transport = paramiko.Transport(('hostname',22))
transport.connect(username='wupeiqi',password='123')
sftp = paramiko.SFTPClient.from_transport(transport)
# 将location.py 上传至服务器 /tmp/test.py
sftp.put('/tmp/location.py', '/tmp/test.py')
# 将remove_path 下载到本地 local_path
sftp.get('remove_path', 'local_path')
transport.close()
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='c1.salt.com', port=22, username='wupeiqi', password='123')
# 执行命令
stdin, stdout, stderr = ssh.exec_command('ls')
# 获取命令结果
result = stdout.read()
# 关闭连接
ssh.close()
连接:
堡垒机