首页 > 代码库 > Python的平凡之路(13)

Python的平凡之路(13)

一、Python的paramiko模块介绍

Python 的paramiko模块,该模块和SSH用于连接远程服务器并执行相关操作

SSH client 用于连接远程服务器并执行基本命令

基于用户名和密码的SSH连接代码如下:

 1 import paramiko
 2 
 3 ssh = paramiko.SSHClient() #创建SSH对象。
 4 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())   #允许连接不在know_hosts文件中的主机
 5 ssh.connect(hostname="10.249.1.230",port=22,username="root",password="123456")   #连接服务器
 6 stdin,stdout,stderr = ssh.exec_command("df")        #执行命令
 7 result = stdout.read()      #获取命令结果
 8 
 9 ssh.close()     #关闭连接
10 print result

执行结果:

C:\Python27\python.exe E:/code/homework/sshclient.py
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/mapper/VolGroup00-LogVol00
9385620 1195720 7713128 14% /
tmpfs 2009884 0 2009884 0% /dev/shm
/dev/vda1 396672 30048 346144 8% /boot

 

SSH基于用户名和密码的连接,实现二:

 1 import paramiko
 2 transport = paramiko.Transport(("10.249.1.230",22))
 3 transport.connect(username="root",password="123456")
 4 ssh = paramiko.SSHClient()
 5 ssh._transport = transport
 6 
 7 #stdin,stdout,stderr = ssh.exec_command("df")
 8 stdin,stdout,stderr = ssh.exec_command("df")
 9 print stdout.read()
10 #print stdout.read()
11 transport.close()

 

二、堡垒机的实现

2.1、实现思路:

 

技术分享

 

2.2、堡垒机执行流程:

1、管理员为用户在服务器上创建账号(将公钥放置在服务器,或者使用用户名和密码的认证);

2、用户登录堡垒机,输入用户名和密码,实现当前用户管理的服务器列表;

3、用户选择需要登录的服务器,并实现自动登录;

4、执行相应的操作并将用户所有的操作记录的审计平台。

 

2.3、堡垒机实现过程

步骤一:实现用户登录:

1 import getpass
2 user = raw_input("username:")
3 pwd =getpass.getpass("password")
4 if user =="root" and pwd =="123":
5     print "登录成功"
6 else:
7     print "登录失败"

步骤二:根据用户获取相关服务器列表:

 1 dic = {
 2     "root":[
 3         "10.249.1.230",
 4         "10.249.1.231",
 5         "www.baidu.com",
 6     ],
 7     "eric":[
 8         "10.249.1.244",
 9     ]
10 }
11 
12 host_list = dic["root"]
13 
14 print "please select:"
15 for index,item in enumerate(host_list,1):
16     print index,item
17 
18 inp = raw_input("your select (No):")
19 inp = input(inp)
20 hostname = host_list[inp-1]
21 port =22

步骤三:根据用户名、私钥登录服务器

 1 tran = paramiko.Transport((hostname,port,))
 2 tran.start_client()
 3 default_path = os.path.join(os.environ["HOME"],".ssh","id_rsa")
 4 key = paramiko.RSAKey.from_private_key_file(default_path)
 5 tran.auth_publickey("jason",key)
 6 
 7 chan = tran.open_session()      #打开一个通道
 8 chan.get_pty()                  #获取一个终端
 9 chan.invoke_shell()             #激活器
10 
11 """
12 利用sys.stdin,肆意妄为执行操作
13 用户在终端输入内容,并将内容发送到远程服务器
14 远程服务器执行命令,并将结果返回
15 在用户终端显示内容
16 """
17 
18 chan.close()
19 tran.close()

建立连接之后,就开始传输数据了,来看下面的实现方式吧!!!!!

实现方式:
 1 while True:
 2     """
 3     监视用户输入和服务器返回数据
 4     sys.stdin 处理用户输入
 5     chan 是之前创建的通道,用于接收服务器返回信息
 6     """
 7     readable,writeable,error = select.select([chan,sys.stdin,],[],[],1)
 8     if chan in readable:
 9         try:
10             x = chan.recv(1024)
11             if len(x) ==0:
12                 print "\r\n*** EOF\r\n",
13                 break
14             sys.stdout.write(x)
15             sys.stdout.flush()
16         except socket.timeout:
17             pass
18     if sys.stdin in readable:
19         inp = sys.stdin.readable()
20         chan.sendall(inp)

  

三、堡垒机下数据库的基本操作

3.1创建数据库:create database [name];  例如:create database messi;    这样就创建了一个数据库名称为:messi.一定要记得后面要加(;)分好哦。。

 

3.2 使用这个数据库   use messi;   即:使用刚刚创建的messi数据库

 

3.3、在数据库中创建数据表,操作如下:记住:创建数据表的时候如下代码第3行,一定要输入几个空格,并使后面的内容对齐哦。如下代码所示:

 1 mysql> create table students
 2     -> (
 3     ->     id int not null auto_increment primary key,
 4     ->     name char(8) not null,
 5     ->     sex char(4) not null,
 6     ->     age tinyint unsigned not null,
 7     ->     tel char(13) null default "-"
 8     -> );
 9 Query OK, 0 rows affected (0.03 sec)
10 
11 mysql>

mysql> show tables;

+-------------------+
| Tables_in_xiaoluo |
+-------------------+
| students |
+-------------------+
1 row in set (0.00 sec)

 

3.4、数据操作:

 插入数据操作:

1 mysql> insert into students(name,sex,age,tel) values("oliver","F",22,"1310000000") 2 -> ; 3 Query OK, 1 row affected (0.00 sec) 4 5 mysql> select * from students; 6 +----+--------+-----+-----+------------+ 7 | id | name | sex | age | tel | 8 +----+--------+-----+-----+------------+ 9 | 1 | oliver | F | 22 | 1310000000 | 10 +----+--------+-----+-----+------------+ 11 1 row in set (0.00 sec)

删除数据操作:

   mysql> delete from students where id = 2;
   Query OK, 1 row affected (0.00 sec)

更新数据操作:

  mysql> update students set tel = "1320000000" where name = "jason";Query OK, 1 row affected (0.00 sec)
  Rows matched: 1 Changed: 1 Warnings: 0

查询数据操作:

mysql> select * from students;
+----+--------+-----+-----+------------+
| id | name | sex | age | tel |
+----+--------+-----+-----+------------+
| 1 | oliver | F | 22 | 1310000000 |
| 5 | jason | M | 18 | 1320000000 |
| 3 | alice | M | 37 | 1330000000 |
| 4 | cindy | F | 27 | 1340000000 |
| 6 | anny | M | 18 | 1350000000 |
| 7 | rice | M | 18 | 1350000000 |
| 8 | bily | M | 27 | 1370000000 |
+----+--------+-----+-----+------------+
7 rows in set (0.00 sec)

 
3.5、Python MySQL API
3.5.1、插入数据
1 import MySQLdb
2 conn = MySQLdb.connect(host="127.0.0.1",user="root",passwd="123.com",db="xiaoluo")
3 cur = conn.cursor()
4 reCount = cur.execute("insert into students(name,sex,age,tel) values(%s,%s,%s,%s)",("jet","M",30,"139999999"))
5 conn.commit()
6 cur.close()
7 conn.close()
8 
9 print reCount

程序运行结果如下:

mysql> select * from students;
+----+--------+-----+-----+------------+
| id | name | sex | age | tel |
+----+--------+-----+-----+------------+
| 1 | oliver | F | 22 | 1310000000 |
| 5 | jason | M | 18 | 1320000000 |
| 3 | alice | M | 37 | 1330000000 |
| 4 | cindy | F | 27 | 1340000000 |
| 6 | anny | M | 18 | 1350000000 |
| 7 | rice | M | 18 | 1350000000 |
| 8 | bily | M | 27 | 1370000000 |
| 9 | alex | M | 23 | 131111111 |
| 10 | jet | M | 30 | 139999999 |
+----+--------+-----+-----+------------+
9 rows in set (0.00 sec)

mysql>

3.5.2 批量数据插入:

 1  1 import MySQLdb
 2  2 conn = MySQLdb.connect(host="127.0.0.1",user="root",passwd="123.com",db="xiaoluo")
 3  3 cur = conn.cursor()
 4  4 #reCount = cur.execute("insert into students(name,sex,age,tel) values(%s,%s,%s,%s)",("jet","M",30,"139999999"))
 5  5 li=[
 6  6     ("AAA","F",31,"138111"),
 7  7     ("BBB","F",32,"138222"),
 8  8     ("CCC","M",33,"138333"),
 9  9 ]
10 10 reCount = cur.executemany("insert into students(name,sex,age,tel) values(%s,%s,%s,%s)",li)
11 11 
12 12 
13 13 conn.commit()
14 14 
15 15 cur.close()
16 16 conn.close()
17 17 
18 18 print reCount
19 
20 插入结果如下所示:
21 mysql> select * from students;
22 +----+--------+-----+-----+------------+
23 | id | name | sex | age | tel |
24 +----+--------+-----+-----+------------+
25 | 1 | oliver | F | 22 | 1310000000 |
26 | 5 | jason | M | 18 | 1320000000 |
27 | 3 | alice | M | 37 | 1330000000 |
28 | 4 | cindy | F | 27 | 1340000000 |
29 | 6 | anny | M | 18 | 1350000000 |
30 | 7 | rice | M | 18 | 1350000000 |
31 | 8 | bily | M | 27 | 1370000000 |
32 | 9 | alex | M | 23 | 131111111 |
33 | 10 | jet | M | 30 | 139999999 |
34 | 11 | AAA | F | 31 | 138111 |
35 | 12 | BBB | F | 32 | 138222 |
36 | 13 | CCC | M | 33 | 138333 |
37 +----+--------+-----+-----+------------+
38 12 rows in set (0.00 sec)

3.5.3 删除表:student的id==1的条目 数据:

 1 import MySQLdb
 2 conn = MySQLdb.connect(host="127.0.0.1",user="root",passwd="123.com",db="xiaoluo")
 3 cur = conn.cursor()
 4 values(%s,%s,%s,%s)",("jet","M",30,"139999999"))
 5 students(name,sex,age,tel) values(%s,%s,%s,%s)",li)
 6 reCount = cur.execute("delete from students where id =1")
 7 
 8 conn.commit()
 9 
10 cur.close()
11 conn.close()
12 
13 print reCount
14 ~                                                                                                                     
15 ~                 

3.5.4 修改student中的所有名字为alin

 1 import MySQLdb
 2 conn = MySQLdb.connect(host="127.0.0.1",user="root",passwd="123.com",db="xiaoluo")
 3 cur = conn.cursor()
 4 
 5 
 6 reCount = cur.execute("update students set name=%s",("alin",))
 7 
 8 
 9 conn.commit()
10 
11 cur.close()
12 conn.close()
13 
14 print reCount

执行结果:

mysql> select * from students;
+----+------+-----+-----+------------+
| id | name | sex | age | tel |
+----+------+-----+-----+------------+
| 5 | alin | M | 18 | 1320000000 |
| 3 | alin | M | 37 | 1330000000 |
| 4 | alin | F | 27 | 1340000000 |
| 6 | alin | M | 18 | 1350000000 |
| 7 | alin | M | 18 | 1350000000 |
| 8 | alin | M | 27 | 1370000000 |
| 9 | alin | M | 23 | 131111111 |
| 10 | alin | M | 30 | 139999999 |
| 11 | alin | F | 31 | 138111 |
| 12 | alin | F | 32 | 138222 |
| 13 | alin | M | 33 | 138333 |
+----+------+-----+-----+------------+
11 rows in set (0.00 sec)

mysql>

3.5.5 查询数据

 1 import MySQLdb
 2 conn = MySQLdb.connect(host="127.0.0.1",user="root",passwd="123.com",db="xiaoluo")
 3 cur = conn.cursor()

12 

14 reCount =cur.execute("select * from students")
15 print cur.fetchone()
16 print cur.fetchone()
17 cur.scroll(-1,mode="relative")
18 print cur.fetchone()
19 print cur.fetchone()
20 cur.scroll(0,mode="absolute")
21 print cur.fetchone()
22 print cur.fetchone()
原数据库表结构:

mysql> select * from students;
+----+------+-----+-----+------------+
| id | name | sex | age | tel |
+----+------+-----+-----+------------+
| 5 | alin | M | 18 | 1320000000 |
| 3 | alin | M | 37 | 1330000000 |
| 4 | alin | F | 27 | 1340000000 |
| 6 | alin | M | 18 | 1350000000 |
| 7 | alin | M | 18 | 1350000000 |
| 8 | alin | M | 27 | 1370000000 |
| 9 | alin | M | 23 | 131111111 |
| 10 | alin | M | 30 | 139999999 |
| 11 | alin | F | 31 | 138111 |
| 12 | alin | F | 32 | 138222 |
| 13 | alin | M | 33 | 138333 |
+----+------+-----+-----+------------+
11 rows in set (0.00 sec)



执行结果:
 
[root@centos6 lab]# python mysql.py 
(5L, ‘alin‘, ‘M‘, 18, ‘1320000000‘)
(3L, ‘alin‘, ‘M‘, 37, ‘1330000000‘)
(3L, ‘alin‘, ‘M‘, 37, ‘1330000000‘)
(4L, ‘alin‘, ‘F‘, 27, ‘1340000000‘)
(5L, ‘alin‘, ‘M‘, 18, ‘1320000000‘)
(3L, ‘alin‘, ‘M‘, 37, ‘1330000000‘)

Python的平凡之路(13)