MySQL常见操作
1)用户管理
创建用户 create user '用户名'@'IP地址' identified by '密码';
删除用户
drop user '用户名'@'IP地址';
修改用户
rename user '用户名'@'IP地址'; to '新用户名'@'IP地址';;
修改密码
set password for '用户名'@'IP地址' = Password('新密码')
2)授权管理
show grants for '用户'@'IP地址' -- 查看权限grant 权限 on 数据库.表 to '用户'@'IP地址' -- 授权revoke 权限 on 数据库.表 from '用户'@'IP地址' -- 取消权限
权限列表
all privileges 除grant外的所有权限 select 仅查权限 select,insert 查和插入权限 ... usage 无访问权限 alter 使用alter table alter routine 使用alter procedure和drop procedure create 使用create table create routine 使用create procedure create temporary tables 使用create temporary tables create user 使用create user、drop user、rename user和revoke all privileges create view 使用create view delete 使用delete drop 使用drop table execute 使用call和存储过程 file 使用select into outfile 和 load data infile grant option 使用grant 和 revoke index 使用index insert 使用insert lock tables 使用lock table process 使用show full processlist select 使用select show databases 使用show databases show view 使用show view update 使用update reload 使用flush shutdown 使用mysqladmin shutdown(关闭MySQL) super 使用change master、kill、logs、purge、 master和set global。还允许mysqladmin调试登陆 replication client 服务器位置的访问 replication slave 由复制从属使用 # 对于目标数据库以及内部其他: 数据库名.* 数据库中的所有 数据库名.表 指定数据库中的某张表 数据库名.存储过程 指定数据库中的存储过程 *.* 所有数据库 # 对用户 用户名@IP地址 用户只能在改IP下才能访问 用户名@192.168.1.% 用户只能在改IP段下才能访问(通配符%表示任意) 用户名@% 用户可以再任意IP下访问(默认IP地址为%) grant all privileges on db1.tb1 TO '用户名'@'IP' grant select on db1.* TO '用户名'@'IP' grant select,insert on *.* TO '用户名'@'IP' revoke select on db1.tb1 from '用户名'@'IP'
3)表操作
创建表
mysql> create table student( -> id int(4) not null auto_increment, #主键 -> name char(20) not null, -> age tinyint(2) not null default '0', -> dept varchar(16) default null, -> primary key(id), # primary 普通索引 -> key index_name(name) # 外键 -> );
自增列
# 如果为某列设置自增列,插入数据时无需设置此列,默认将自增(表中只能有一个自增列) create table tb1( nid int not null auto_increment primary key, num int null ) 或 create table tb1( nid int not null auto_increment, num int null, index(nid) ) 注意:1、对于自增列,必须是索引(含主键)。 2、对于自增可以设置步长和起始值 show session variables like 'auto_inc%'; set session auto_increment_increment=2; set session auto_increment_offset=10; shwo global variables like 'auto_inc%'; set global auto_increment_increment=2; set global auto_increment_offset=10;
主键
# 一种特殊的唯一索引,不允许有空值,如果主键使用单个列,则它的值必须唯一,如果是多列,# 则其组合必须唯一。 create table tb1( nid int not null auto_increment primary key, num int null ) 或 create table tb1( nid int not null, num int not null, primary key(nid,num) )
外键
# 一个特殊的索引,只能是指定内容 creat table color( nid int not null primary key, name char(16) not null ) create table fruit( nid int not null primary key, smt char(32) null , color_id int not null, constraint fk_cc foreign key (color_id) references color(nid) )
删除表
# drop table 表名 (清除数据库表占用空间)
清空表
# deletedelete from 表名 (只清空数据)truncate table 表名 (删除表结构)
修改表
# 添加列: alter table 表名 add 列名 类型# 删除列: alter table 表名 drop column 列名# 修改列: alter table 表名 modify column 列名 类型; -- 类型 alter table 表名 change 原列名 新列名 类型; -- 列名,类型# 添加主键: alter table 表名 add primary key(列名);# 删除主键: alter table 表名 drop primary key; alter table 表名 modify 列名 int, drop primary key;# 添加外键: alter table 从表 add constraint 外键名称(形如:FK_从表_主表) foreign key 从表(外键字段) references 主表(主键字段);# 删除外键: alter table 表名 drop foreign key 外键名称# 修改默认值: ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;# 删除默认值: ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;
4)重要的数据类型
# TINYINT: 1字节 # INT : 4字节 正常大小整数类型# BIGINT : 8字节 # CHAR : m字节 定长字符串类型,当存储时总是用空格填满右边到指定长度# VARCHAR : m+1字节 变长字符串类型# DATE: 3字节
5)基本操作
增
insert into 表 (列名,列名...) values (值,值,值...) insert into 表 (列名,列名...) values (值,值,值...),(值,值,值...) insert into 表 (列名,列名...) select (列名,列名...) from 表
删
delete from 表 delete from 表 where id=1 and name='user01'
改
update 表 set name = 'user01' where id>1
查
select * from 表 select * from 表 where id > 1 select nid,name,gender as gg from 表 where id > 1
条件查
1、条件 select * from 表 where id > 1 and name != 'alex' and num = 12; select * from 表 where id between 5 and 16; select * from 表 where id in (11,22,33) select * from 表 where id not in (11,22,33) select * from 表 where id in (select nid from 表) 2、通配符 select * from 表 where name like 'ale%' - ale开头的所有(多个字符串) select * from 表 where name like 'ale_' - ale开头的所有(一个字符) 3、限制 select * from 表 limit 5; - 前5行 select * from 表 limit 4,5; - 从第4行开始的5行 select * from 表 limit 5 offset 4 - 从第4行开始的5行 4、排序 select * from 表 order by 列 asc - 根据 “列” 从小到大排列 select * from 表 order by 列 desc - 根据 “列” 从大到小排列 select * from 表 order by 列1 desc,列2 asc - 根据 “列1” 从大到小排列, 如果相同则按列2从小到大排序 5、分组 select num from 表 group by num select num,nid from 表 group by num,nid select num,nid from 表 where nid > 10 group by num,nid order nid desc select num,nid,count(*),sum(score),max(score),min(score) from 表 group by num,nid select num from 表 group by num having max(id) > 10 特别的:group by 必须在where之后,order by之前 6、连表 无对应关系则不显示 select A.num, A.name, B.name from A,B Where A.nid = B.nid 无对应关系则不显示 select A.num, A.name, B.name from A inner join B on A.nid = B.nid A表所有显示,如果B中无对应关系,则值为null select A.num, A.name, B.name from A left join B on A.nid = B.nid B表所有显示,如果B中无对应关系,则值为null select A.num, A.name, B.name from A right join B on A.nid = B.nid 7、组合 组合,自动处理重合 select nickname from A union select name from B 组合,不处理重合 select nickname from A union all select name from B
6)其他常见操作
# 启动原理单实例启动mysqld_safe --datadir="$datadir" --pid-file="$mysqld_pid_file_path"多实例启动mysqld_safe --defaults-file=/data/${port}/my.cnf停止MySQLmysqladmin -u ${mysql_user} -p${mysql_pwd} -S /data/${port}/mysql.sock shutdown # 找回root密码单示例/etc/init.d/mysqld stopmysqld_safe --skip-grant-tables --user=mysql &/etc/init.d/mysqld startmysqlmysql> update mysql.user set password=PASSWORD("123") where user='root' and host='localhost';mysql> flush privileges;pkill mysqld/etc/init.d/mysqld start多示例mysqld_safe --defaults-file=/data/3306/my.cnf --skip-grant-table &mysql -S /data/3306/mysql.sockupdate mysql.user set password=PASSWORD("123") where user='root' and host='localhost';mysqladmin -uroot -poldboy1234 -S /data/3306/mysql.sock shutdownmysqld_safe --defaults-file=/data/3306/my.cnf &
Pymsql
Pymsql是操作MySQL的模块,功能和MySQLdb几乎相同
安装
# pip3 install pymsql
执行MySQL
import pymysql # 创建连接conn = pymysql.connect(host='10.0.0.111', port=3306, user='root', passwd='123', db='t1') # 创建游标cursor = conn.cursor() # 执行SQL,并返回收影响行数effect_row = cursor.execute("update hosts set host = '1.1.1.3'")print(effect_row) # 执行SQL,并返回受影响行数# effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,)) # 执行SQL,并返回受影响行数# effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)]) # 提交,不然无法保存新建或者修改的数据conn.commit() # 关闭游标cursor.close() # 关闭连接conn.close()
获取最新自增ID
import pymysql conn = pymysql.connect(host='10.0.0.111', port=3306, user='root', passwd='123', db='t1') cursor = conn.cursor() cursor.executemany("insert into hosts(host,color_id) values(%s,%s)", [("1.1.1.11", 1), ("1.1.1.11", 2)]) conn.commit() cursor.close() conn.close() # 获取最新自增IDnew_id = cursor.lastrowidprint(new_id)
获取查询数据
import pymysql conn = pymysql.connect(host='10.0.0.111', port=3306, user='root', passwd='123', db='t1')cursor = conn.cursor() # fetch 到的数据类型是元组 如果想得到字典类型 可以使用下面# cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute("select * from hosts") # 获取第一行数据# row_1 = cursor.fetchone() # 获取前n行数据# row_2 = cursor.fetchmany(3) # 获取所有数据row_3 = cursor.fetchall()print(row_3) conn.commit()cursor.close()conn.close()
在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:
cursor.scroll(1,mode='relative') # 相对当前位置移动cursor.scroll(2,mode='absolute') # 相对绝对位置移动
SQLAchemy
SQLAchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作,简言之便是:将对象转换成SQL,然后使用数据API执行SQL并获取执行结果
SQLAlchemy本身无法操作数据库,其必须依赖pymsql等第三方插件,Dialect用于和数据库API进行交流,根据配置文件的不同调用不同的数据库API,从而实现数据库的操作:
# MySQL-Python mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname> # pymysql mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>] # MySQL-Connector mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname> # cx_Oracle oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...] # 更多详见:http://docs.sqlalchemy.org/en/latest/dialects/index.html
使用 Engine/ConnectionPooling/Dialect 进行数据库操作,Engine使用ConnectionPooling连接数据库,然后再通过Dialect执行SQL语句。
from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://root:123@10.0.0.111:3306/t1", max_overflow=5) # 执行SQLcur = engine.execute( "INSERT INTO hosts (host, color_id) VALUES ('1.1.1.22', 3)") # 新插入行自增ID# cur.lastrowid # 执行SQL# cur = engine.execute(# "INSERT INTO hosts (host, color_id) VALUES(%s, %s)",[('1.1.1.22', 3),('1.1.1.221', 3),]# ) # 执行SQL# cur = engine.execute(# "INSERT INTO hosts (host, color_id) VALUES (%(host)s, %(color_id)s)",# host='1.1.1.99', color_id=3# ) # 执行SQL# cur = engine.execute('select * from hosts') # 获取第一行数据# cur.fetchone()# 获取第n行数据# cur.fetchmany(3)# 获取所有数据# row = cur.fetchall()# print(row)
ORM功能使用
使用 ORM/Schema Type/SQL Expression Language/Engine/ConnectionPooling/Dialect 所有组件对数据进行操作。根据类创建对象,对象转换成SQL,执行SQL。
1)创建表
from sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Indexfrom sqlalchemy.orm import sessionmaker, relationshipfrom sqlalchemy import create_engine engine = create_engine("mysql+pymysql://root:123@10.0.0.111:3306/t1", max_overflow=5) Base = declarative_base() # 创建单表class Users(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(32)) extra = Column(String(16)) __table_args__ = ( UniqueConstraint('id', 'name', name='uix_id_name'), Index('ix_id_name', 'name', 'extra'), ) # 一对多class Favor(Base): __tablename__ = 'favor' nid = Column(Integer, primary_key=True) caption = Column(String(50), default='red', unique=True) class Person(Base): __tablename__ = 'person' nid = Column(Integer, primary_key=True) name = Column(String(32), index=True, nullable=True) favor_id = Column(Integer, ForeignKey("favor.nid")) # 多对多class Group(Base): __tablename__ = 'group' id = Column(Integer, primary_key=True) name = Column(String(64), unique=True, nullable=False) port = Column(Integer, default=22) class Server(Base): __tablename__ = 'server' id = Column(Integer, primary_key=True, autoincrement=True) hostname = Column(String(64), unique=True, nullable=False) class ServerToGroup(Base): __tablename__ = 'servertogroup' nid = Column(Integer, primary_key=True, autoincrement=True) server_id = Column(Integer, ForeignKey('server.id')) group_id = Column(Integer, ForeignKey('group.id')) def init_db(): Base.metadata.create_all(engine) # Base.metadata.create_all(engine) def drop_db(): Base.metadata.drop_all(engine) # Base.metadata.drop_all(engine)
2)操作表
# !/usr/bin/env python# -*- coding:utf-8 -*-# Author:pylarva# bolg:www.lichengbing.com from sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Indexfrom sqlalchemy.orm import sessionmaker, relationshipfrom sqlalchemy import create_engine engine = create_engine("mysql+pymysql://root:123@10.0.0.111:3306/t1", max_overflow=5) Base = declarative_base() # 创建单表class Users(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(32)) extra = Column(String(16)) __table_args__ = ( UniqueConstraint('id', 'name', name='uix_id_name'), Index('ix_id_name', 'name', 'extra'), ) def __repr__(self): return "%s-%s" %(self.id, self.name) # 一对多class Favor(Base): __tablename__ = 'favor' nid = Column(Integer, primary_key=True) caption = Column(String(50), default='red', unique=True) def __repr__(self): return "%s-%s" %(self.nid, self.caption) class Person(Base): __tablename__ = 'person' nid = Column(Integer, primary_key=True) name = Column(String(32), index=True, nullable=True) favor_id = Column(Integer, ForeignKey("favor.nid")) # 与生成表结构无关,仅用于查询方便 favor = relationship("Favor", backref='pers') # 多对多class ServerToGroup(Base): __tablename__ = 'servertogroup' nid = Column(Integer, primary_key=True, autoincrement=True) server_id = Column(Integer, ForeignKey('server.id')) group_id = Column(Integer, ForeignKey('group.id')) group = relationship("Group", backref='s2g') server = relationship("Server", backref='s2g') class Group(Base): __tablename__ = 'group' id = Column(Integer, primary_key=True) name = Column(String(64), unique=True, nullable=False) port = Column(Integer, default=22) # group = relationship('Group',secondary=ServerToGroup,backref='host_list') class Server(Base): __tablename__ = 'server' id = Column(Integer, primary_key=True, autoincrement=True) hostname = Column(String(64), unique=True, nullable=False) def init_db(): Base.metadata.create_all(engine) def drop_db(): Base.metadata.drop_all(engine) Session = sessionmaker(bind=engine)session = Session() # 增 obj = Users(name="alex0", extra='sb')session.add(obj)session.add_all([ Users(name="alex1", extra='sb'), Users(name="alex2", extra='sb'),])session.commit() # 删 session.query(Users).filter(Users.id > 2).delete()session.commit() # 改 session.query(Users).filter(Users.id > 2).update({"name" : "099"})session.query(Users).filter(Users.id > 2).update({Users.name: Users.name + "099"}, synchronize_session=False)session.query(Users).filter(Users.id > 2).update({"num": Users.num + 1}, synchronize_session= "evaluate")session.commit() # 查 ret = session.query(Users).all()ret = session.query(Users.name, Users.extra).all()ret = session.query(Users).filter_by(name='alex').all()ret = session.query(Users).filter_by(name='alex').first() # 条件ret = session.query(Users).filter_by(name='alex').all()ret = session.query(Users).filter(Users.id > 1, Users.name == 'eric').all()ret = session.query(Users).filter(Users.id.between(1, 3), Users.name == 'eric').all()ret = session.query(Users).filter(Users.id.in_([1,3,4])).all()ret = session.query(Users).filter(~Users.id.in_([1,3,4])).all()ret = session.query(Users).filter(Users.id.in_(session.query(Users.id).filter_by(name='eric'))).all()from sqlalchemy import and_, or_ret = session.query(Users).filter(and_(Users.id > 3, Users.name == 'eric')).all()ret = session.query(Users).filter(or_(Users.id < 2, Users.name == 'eric')).all()ret = session.query(Users).filter( or_( Users.id < 2, and_(Users.name == 'eric', Users.id > 3), Users.extra != "" )).all() # 通配符ret = session.query(Users).filter(Users.name.like('e%')).all()ret = session.query(Users).filter(~Users.name.like('e%')).all() # 限制ret = session.query(Users)[1:2] # 排序ret = session.query(Users).order_by(Users.name.desc()).all()ret = session.query(Users).order_by(Users.name.desc(), Users.id.asc()).all() # 分组from sqlalchemy.sql import func ret = session.query(Users).group_by(Users.extra).all()ret = session.query( func.max(Users.id), func.sum(Users.id), func.min(Users.id)).group_by(Users.name).all() ret = session.query( func.max(Users.id), func.sum(Users.id), func.min(Users.id)).group_by(Users.name).having(func.min(Users.id) >2).all() # 连表 ret = session.query(Users, Favor).filter(Users.id == Favor.nid).all() ret = session.query(Person).join(Favor).all() ret = session.query(Person).join(Favor, isouter=True).all() # 组合q1 = session.query(Users.name).filter(Users.id > 2)q2 = session.query(Favor.caption).filter(Favor.nid < 2)ret = q1.union(q2).all() q1 = session.query(Users.name).filter(Users.id > 2)q2 = session.query(Favor.caption).filter(Favor.nid < 2)ret = q1.union_all(q2).all()
3)表结构操作联系
from sqlalchemy import create_engine,and_,or_,func,Tablefrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import Column, Integer, String,ForeignKey,UniqueConstraint,DateTimefrom sqlalchemy.orm import sessionmaker,relationship Base = declarative_base() #生成一个SqlORM 基类 # 服务器账号和组# HostUser2Group = Table('hostuser_2_group',Base.metadata,# Column('hostuser_id',ForeignKey('host_user.id'),primary_key=True),# Column('group_id',ForeignKey('group.id'),primary_key=True),# ) # 用户和组关系表,用户可以属于多个组,一个组可以有多个人UserProfile2Group = Table('userprofile_2_group',Base.metadata, Column('userprofile_id',ForeignKey('user_profile.id'),primary_key=True), Column('group_id',ForeignKey('group.id'),primary_key=True),) # 程序登陆用户和服务器账户,一个人可以有多个服务器账号,一个服务器账号可以给多个人用UserProfile2HostUser= Table('userprofile_2_hostuser',Base.metadata, Column('userprofile_id',ForeignKey('user_profile.id'),primary_key=True), Column('hostuser_id',ForeignKey('host_user.id'),primary_key=True),) class Host(Base): __tablename__='host' id = Column(Integer,primary_key=True,autoincrement=True) hostname = Column(String(64),unique=True,nullable=False) ip_addr = Column(String(128),unique=True,nullable=False) port = Column(Integer,default=22) def __repr__(self): return "<id=%s,hostname=%s, ip_addr=%s>" %(self.id, self.hostname, self.ip_addr) class HostUser(Base): __tablename__ = 'host_user' id = Column(Integer,primary_key=True) AuthTypes = [ (u'ssh-passwd',u'SSH/Password'), (u'ssh-key',u'SSH/KEY'), ] # auth_type = Column(ChoiceType(AuthTypes)) auth_type = Column(String(64)) username = Column(String(64),unique=True,nullable=False) password = Column(String(255)) host_id = Column(Integer,ForeignKey('host.id')) # groups = relationship('Group', # secondary=HostUser2Group, # backref='host_list') __table_args__ = (UniqueConstraint('host_id','username', name='_host_username_uc'),) def __repr__(self): return "<id=%s,name=%s>" %(self.id,self.username) class Group(Base): __tablename__ = 'group' id = Column(Integer,primary_key=True) name = Column(String(64),unique=True,nullable=False) def __repr__(self): return "<id=%s,name=%s>" %(self.id,self.name) class UserProfile(Base): __tablename__ = 'user_profile' id = Column(Integer,primary_key=True) username = Column(String(64),unique=True,nullable=False) password = Column(String(255),nullable=False) # host_list = relationship('HostUser', # secondary=UserProfile2HostUser, # backref='userprofiles') # groups = relationship('Group', # secondary=UserProfile2Group, # backref='userprofiles') def __repr__(self): return "<id=%s,name=%s>" %(self.id,self.username) class AuditLog(Base): __tablename__ = 'audit_log' id = Column(Integer,primary_key=True) userprofile_id = Column(Integer,ForeignKey('user_profile.id')) hostuser_id = Column(Integer,ForeignKey('host_user.id')) action_choices2 = [ (u'cmd',u'CMD'), (u'login',u'Login'), (u'logout',u'Logout'), ] action_type = Column(ChoiceType(action_choices2)) #action_type = Column(String(64)) cmd = Column(String(255)) date = Column(DateTime) # user_profile = relationship("UserProfile") #bind_host = relationship("BindHost") engine = create_engine("mysql+pymsql://root:123@localhost:3306/stupid_jumpserver",echo=False)Base.metadata.create_all(engine) #创建所有表结构
Paramiko
paramiko模块,基于SSH用于连接远程服务器并执行相关操作。
安装
# pip3 install paramiko
使用
用于用户名和密码连接
import paramiko # 创建SSH对象ssh = paramiko.SSHClient() # 允许连接不在know_hosts文件中的主机ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接服务器ssh.connect(hostname='www.lichengbing.cn', port=22, username='root', password='123456') # 执行命令stdin, stdout, stderr = ssh.exec_command('ls') # 获取命令结果result = stdout.read()print(result) # 关闭连接ssh.close()
SSHclient 封装 transport
import paramiko transport = paramiko.Transport(('www.lichengbing.cn', 22))transport.connect(username='root', password='123456') ssh = paramiko.SSHClient()ssh._transport = transport stdin, stdout, stderr = ssh.exec_command('df')print(stdout.read()) transport.close()
基于公钥密钥连接
import paramiko private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa') # 创建SSH对象ssh = paramiko.SSHClient() # 允许连接不在know_hosts文件中的主机ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接服务器ssh.connect(hostname='c1.salt.com', port=22, username='wupeiqi', key=private_key) # 执行命令stdin, stdout, stderr = ssh.exec_command('df') # 获取命令结果result = stdout.read() # 关闭连接ssh.close()
SSHclient 封装 transport
import paramiko private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa') transport = paramiko.Transport(('hostname', 22))transport.connect(username='root', pkey=private_key) ssh = paramiko.SSHClient()ssh._transport = transport stdin, stdout, stderr = ssh.exec_command('df') transport.close()
SFTPClient
用于连接远程服务器并执行上传下载
基于用户名密码上传下载
import paramiko transport = paramiko.Transport(('hostname',22))transport.connect(username='root',password='123') sftp = paramiko.SFTPClient.from_transport(transport) # 将location.py 上传至服务器 /tmp/test.pysftp.put('/tmp/location.py', '/tmp/test.py') # 将remove_path 下载到本地 local_pathsftp.get('remove_path', 'local_path') transport.close()
基于公钥密钥上传下载:
import paramiko private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')transport = paramiko.Transport(('hostname', 22))transport.connect(username='root', pkey=private_key ) sftp = paramiko.SFTPClient.from_transport(transport) # 将location.py 上传至服务器 /tmp/test.pysftp.put('/tmp/location.py', '/tmp/test.py') # 将remove_path 下载到本地 local_pathsftp.get('remove_path', 'local_path') transport.close()
本文出自 “改变从每一天开始” 博客,请务必保留此出处http://lilongzi.blog.51cto.com/5519072/1887086