Python with MySQLdb, pymssql module connects remote database via Sshtunnel

Source: Internet
Author: User

Security, access to the database is mostly limited, so there is a direct problem is that often, on other machines (such as their own local), is not able to access the database, to daily use caused great inconvenience. So a few days ago to do a demand, is that on any machine can ssh to a database on the white list of the machine, and then access the database.

Recommended by the People, query a tool called Sshtunnel, need to be installed on the machine you want to log on to the database.

Basic introduction of Sshtunnel: Http://sshtunnel.readthedocs.io/en/latest/?badge=latest

The side of the figure 2, exactly the scenario we described, the database on a remote server, can only be together with another server to access, but we need to SSH to this server locally

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

The original code is below this:

1 ImportParamiko2  fromSshtunnelImportSshtunnelforwarder3 4 With Sshtunnelforwarder (5(REMOTE_SERVER_IP, 443),6Ssh_username="",7ssh_pkey="/var/ssh/rsa_key",8ssh_private_key_password="Secret",9Remote_bind_address= (PRIVATE_SERVER_IP, 22),TenLocal_bind_address= ('0.0.0.0', 10022) One ) as tunnel: AClient =Paramiko. Sshclient () - Client.load_system_host_keys () - Client.set_missing_host_key_policy (Paramko. Autoaddpolicy ()) theClient.connect ('127.0.0.1', 10022) -     #Do some operations with client session - client.close () -  + Print('finish!')

Connect to MySQL Database

When you connect to the MySQL database, you see a programmer on the Internet that has implemented it: Python uses the MySQLdb module to connect to MySQL via the SSH tunnel

The code is as follows:

1 ImportMySQLdb2  fromSshtunnelImportSshtunnelforwarder3 4 With Sshtunnelforwarder (5('sshhost.domain.com', 22),#configuration of the B machine6ssh_password="sshpasswd",7Ssh_username="Sshusername",8Remote_bind_address= ('mysqlhost.domain.com', Mysql.port)) as server:#the configuration of a machine9 Tenconn = MySQLdb.connect (host='127.0.0.1',#It must be 127.0.0.1 here . Oneport=Server.local_bind_port, AUser='User', -Passwd='Password', -db='dbname')

Then the next query what, directly written in with there side, and Conn alignment on it.

One problem for my side is that because we are in a separate function for the database connection part, it is often not together with the query Insert delete Update operation from other databases, so with the feature of the with as is that the object is destroyed when you leave the scope. Other functions can not be used, there will be a situation is, the connection, but the object is destroyed, the results of the query directly display this error: Operationalerror: (2006, ' MySQL server has gone away '), and online query This error, mostly because you query the SQL operation is too long, or the data sent is too large, but I this place is actually because of the scope of the with AS, resulting in the connection and closed off, so the result occurs.

There is an article written in detail about with AS. Understand the with...as in Python ... Grammar

So I changed the SSH code above, like the Sshtunnel document inside the corresponding code, the same, the Sshtunnelforwarder out of the object assigned to the server, and then start the server, and then a series of operations, and then stop off.

Originally the database connection we wrote a separate function, after the change, the direct also put in this function is good, replace the original connect statement.

1 defConnect (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 9Server =Sshtunnelforwarder (Ten('sshhost.domain.com', 22),#configuration of the B machine Onessh_password='Ssh_password', ASsh_username='Ssh_username', -Remote_bind_address= ('mysqlhost.domain.com', Mysql.port) -     ) the Server.start () -  -Self.client = MySQLdb.connect (host='127.0.0.1',#It must be 127.0.0.1 here . -port=Server.local_bind_port, +User='username', -Passwd='Password', +db='dbname')

Then in the query update delete operations, the first connection to the database is good, with self.client.

Connect to SQL Server database

Consistent with MySQL, but DB has to be aware that SQL Server is database, Then it is pymssql.connect, but this place also said I stepped on a pit, I finished writing SQL Server after the connection is not connected to the database, later found that the version of the problem, I have updated the local SQL Server can be. The feeling version is a big pit.

Python with MySQLdb, pymssql module connects remote database via Sshtunnel

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.