简体   繁体   中英

Opening SSH session and running commands in different terminal in Python

Below is the process I am doing manually and I want to automate it in Python.

  1. I am opening SSH terminal to MySQL server using below command
cf ssh -L 63380:100.120.11.22:3380 appname
  1. Once this SSH is established I am doing ctrl + t to open a new terminal tab and run below command to create DB objects
mysql -u myuser -h 0 -pmypassword -D mydbname -P 3380 < init_db/mysql/schema.ddl

Now I have written Python code for step 1 like below

process = subprocess.Popen("cf ssh -L 63380:100.120.11.22:3380 appname",shell = True)

It opens SSH terminal but when ran second step using below code it does not connect to opened SSH terminal it says not able to connect to MySQL server.

pro = subprocess.Popen("mysql -u myuser -h 0 -pmypassword -D mydbname -P 3380 < init_db/mysql/schema.ddl", stdout=subprocess.PIPE,shell=True, preexec_fn=os.setsid) 

I have searched and tried other options like writing step 2 in different program and calling from first program after SSH is established but of no use.

Kindly let me know if any solution is available in Python for this. Env: mac, pcf.

It looks to me like this command:

cf ssh -L 63380:100.120.11.22:3380 appname

ssh's to your CloudFoundry application server and forwards any connection on your local machine's port 63380 to the remote port 3380. So it seems like your mysql connection should be:

mysql -u myuser -h localhost -pmypassword -D mydbname -P 63380 < init_db/mysql/schema.ddl

where init_db/mysql/schema.ddl is on your local machine.

I'm not completely sure if this will work with CloudFoundry, but with ssh you can run a remote command like this:

ssh username@<host or ip> <command>
#for example:
ssh myname@example.com ls -al

So you might try putting ~/init_db/mysql/schema.dll on the server and use this command:

cf ssh appname mysql -u myuser -pmypassword -Dmydbname -P 3380 < ~/init_db/mysql/schema.dll

You should be able to drop that command into python's subprocess.Popen() .

I found way of avoiding the ssh to mysql. There is a cf mysql plugin by which we can connect to cf mysql services and execute the queries. More details can be found at: https://github.com/andreasf/cf-mysql-plugin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM