Python uses MySQLdb, the pymssql module connects to the remote database through sshtunnel and reproduces

Reprinted from https://www.cnblogs.com/luyingfeng/p/6386093.html

For the sake of security, the access to the database is mostly restricted, so there is a direct problem that most of the time, the database cannot be accessed on other machines (such as your own local), which causes a lot of daily use. inconvenient. So I made a request a few days ago, I hope that any machine can ssh to a machine on the database whitelist, and then access the database.

After being recommended, I checked a tool called sshtunnel, which needs to be installed on the machine where you want to log in to the database.

Basic introduction to sshtunnel:  http://sshtunnel.readthedocs.io/en/latest/?badge=latest

Figure 2 here is exactly the scenario we described. The database is on a remote server and can only be accessed by another server with the same location, but we need to ssh to this server locally.

 

But the code involved in this is server-related, and the remote connection is the server. What we need is the database of the remote server. This is the same, only need to change the second half of the code.

The original code is as follows:

copy code
1 import paramiko
 2 from sshtunnel import SSHTunnelForwarder
 3
 4 with SSHTunnelForwarder(
 5     (REMOTE_SERVER_IP, 443),
 6     ssh_username="",
 7     ssh_pkey="/var/ssh/rsa_key",
 8     ssh_private_key_password="secret",
 9     remote_bind_address=(PRIVATE_SERVER_IP, 22),
10     local_bind_address=('0.0.0.0', 10022)
11 ) as tunnel:
12     client = paramiko.SSHClient()
13     client.load_system_host_keys()
14     client.set_missing_host_key_policy(paramko.AutoAddPolicy())
15     client.connect('127.0.0.1', 10022)
16     # do some operations with client session
17     client.close()
18
19 print('FINISH!')
copy code

connect to mysql database

When connecting to the mysql database, I saw that a programmer on the Internet has implemented it:  python uses the mysqldb module to connect to mysql through the ssh tunnel

code show as below:

copy code
1 import MySQLdb
 2 from sshtunnel import SSHTunnelForwarder
 3
 4 with SSHTunnelForwarder(
 5 ('sshhost.domain.com', 22), #B machine configuration
 6          ssh_password="sshpasswd",
 7          ssh_username="sshusername",
 8 remote_bind_address=('mysqlhost.domain.com', mysql.port)) as server: #A machine configuration
 9
10 conn = MySQLdb.connect(host='127.0.0.1', #must be 127.0.0.1 here
11                            port=server.local_bind_port,
12                            user='user',
13                            passwd='password',
14                            db='dbname')
copy code

 Then the next query or something can be written directly in with and aligned with conn.

For me, there is a problem, because we often use a separate function for the database connection part, and the query, insert, delete, and update operations of other databases are often not together. In this case, with as has a feature that , leaving this scope, the object is destroyed, and it is useless in other functions. There will also be a situation where the connection is connected, but the object is destroyed again, and the result is directly queried. This error is displayed: OperationalError: (2006, 'MySQL server has gone away'), and the online query for this error is mostly because the sql operation you are querying takes too long, or the transmitted data is too large, but my The place is actually because the scope of with as is out, and the connection is closed again, so this result occurs.

Regarding with as, there is an article written in great detail. Understand the with...as... syntax in Python

So I changed the ssh code above, like the code corresponding to Figure 1 in the sshtunnel document, and assigned the object from SSHTunnelForwarder to the server, then started the server, and then stopped after a series of operations.

Originally, we wrote a separate function for the database connection. After the change, we can directly put it in this function instead of the original connect statement.

copy code
1 def connect(self):
 2     '''
 3     self.client = MySQLdb.connect(host=self.server, port=self.port, user=self.user,
 4                                   passwd=self.password, db=self.database,
 5                                   charset=self.charset)
 6     # log.info('Connect to MySQL Server: ' + self.server)
 7     '''
 8
 9     server = SSHTunnelForwarder(
10 ('sshhost.domain.com', 22), # B machine configuration
11             ssh_password='ssh_password',
12             ssh_username='ssh_username',
13             remote_bind_address=('mysqlhost.domain.com', mysql.port)
14     )
15     server.start()
16
17 self.client = MySQLdb.connect(host='127.0.0.1', # must be 127.0.0.1 here
18                                   port=server.local_bind_port,
19                                   user='username',
20                                   passwd='password',
21                                   db='dbname')
copy code

Then when performing operations such as query, update, delete, etc., just connect to the database first, and use self.client.

Connect to sqlserver database

It is the same as mysql, but pay attention to db, SQLServer is database, and then pymssql.connect is fine, but this place also has a pit I stepped on. After I wrote sqlserver, I couldn't connect to the database. , I later found out that it is a version problem, I can update the local SQL Server. The version feels like a big hole

For the sake of security, the access to the database is mostly restricted, so there is a direct problem that most of the time, the database cannot be accessed on other machines (such as your own local), which causes a lot of daily use. inconvenient. So I made a request a few days ago, I hope that any machine can ssh to a machine on the database whitelist, and then access the database.

After being recommended, I checked a tool called sshtunnel, which needs to be installed on the machine where you want to log in to the database.

Basic introduction to sshtunnel:  http://sshtunnel.readthedocs.io/en/latest/?badge=latest

Figure 2 here is exactly the scenario we described. The database is on a remote server and can only be accessed by another server with the same location, but we need to ssh to this server locally.

 

But the code involved in this is server-related, and the remote connection is the server. What we need is the database of the remote server. This is the same, only need to change the second half of the code.

The original code is as follows:

copy code
1 import paramiko
 2 from sshtunnel import SSHTunnelForwarder
 3
 4 with SSHTunnelForwarder(
 5     (REMOTE_SERVER_IP, 443),
 6     ssh_username="",
 7     ssh_pkey="/var/ssh/rsa_key",
 8     ssh_private_key_password="secret",
 9     remote_bind_address=(PRIVATE_SERVER_IP, 22),
10     local_bind_address=('0.0.0.0', 10022)
11 ) as tunnel:
12     client = paramiko.SSHClient()
13     client.load_system_host_keys()
14     client.set_missing_host_key_policy(paramko.AutoAddPolicy())
15     client.connect('127.0.0.1', 10022)
16     # do some operations with client session
17     client.close()
18
19 print('FINISH!')
copy code

connect to mysql database

When connecting to the mysql database, I saw that a programmer on the Internet has implemented it:  python uses the mysqldb module to connect to mysql through the ssh tunnel

code show as below:

copy code
1 import MySQLdb
 2 from sshtunnel import SSHTunnelForwarder
 3
 4 with SSHTunnelForwarder(
 5 ('sshhost.domain.com', 22), #B machine configuration
 6          ssh_password="sshpasswd",
 7          ssh_username="sshusername",
 8 remote_bind_address=('mysqlhost.domain.com', mysql.port)) as server: #A machine configuration
 9
10 conn = MySQLdb.connect(host='127.0.0.1', #must be 127.0.0.1 here
11                            port=server.local_bind_port,
12                            user='user',
13                            passwd='password',
14                            db='dbname')
copy code

 Then the next query or something can be written directly in with and aligned with conn.

For me, there is a problem, because we often use a separate function for the database connection part, and the query, insert, delete, and update operations of other databases are often not together. In this case, with as has a feature that , leaving this scope, the object is destroyed, and it is useless in other functions. There will also be a situation where the connection is connected, but the object is destroyed again, and the result is directly queried. This error is displayed: OperationalError: (2006, 'MySQL server has gone away'), and the online query for this error is mostly because the sql operation you are querying takes too long, or the transmitted data is too large, but my The place is actually because the scope of with as is out, and the connection is closed again, so this result occurs.

Regarding with as, there is an article written in great detail. Understand the with...as... syntax in Python

So I changed the ssh code above, like the code corresponding to Figure 1 in the sshtunnel document, and assigned the object from SSHTunnelForwarder to the server, then started the server, and then stopped after a series of operations.

Originally, we wrote a separate function for the database connection. After the change, we can directly put it in this function instead of the original connect statement.

copy code
1 def connect(self):
 2     '''
 3     self.client = MySQLdb.connect(host=self.server, port=self.port, user=self.user,
 4                                   passwd=self.password, db=self.database,
 5                                   charset=self.charset)
 6     # log.info('Connect to MySQL Server: ' + self.server)
 7     '''
 8
 9     server = SSHTunnelForwarder(
10 ('sshhost.domain.com', 22), # B machine configuration
11             ssh_password='ssh_password',
12             ssh_username='ssh_username',
13             remote_bind_address=('mysqlhost.domain.com', mysql.port)
14     )
15     server.start()
16
17 self.client = MySQLdb.connect(host='127.0.0.1', # must be 127.0.0.1 here
18                                   port=server.local_bind_port,
19                                   user='username',
20                                   passwd='password',
21                                   db='dbname')
copy code

Then when performing operations such as query, update, delete, etc., just connect to the database first, and use self.client.

Connect to sqlserver database

It is the same as mysql, but pay attention to db, SQLServer is database, and then pymssql.connect is fine, but this place also has a pit I stepped on. After I wrote sqlserver, I couldn't connect to the database. , I later found out that it is a version problem, I can update the local SQL Server. The version feels like a big hole

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324940454&siteId=291194637