Search code examples
pythonsshparamikowindows-shell

Not able to execute remotely placed ssh script with parameter using paramiko ssh client


My code read like this-

import paramiko
import time
import sys

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def runScripts():
    parameter1 = 1000
    client.connect('mysite.com', username='user', password='pass')
    print ("Logged in into Site server")
    stdin, stdout, stderr = client.exec_command("cd parent_folder/Sub_folder/script_folder; ./script1.sh %s" % parameter1)
    print ("Script executed perfectly")
    client.close()

runScripts()

And i got output on console as below-

Logged in into Site server
Script executed perfectly 

But checked the file which was going to get affected due to the script.sh 1000 has no changes. the problem is not with script.sh because i can run the same manually and it behaves as expected.

Is client not able to detect end of the command?


Solution

  • I found out answer to my own query on a video over youtube for interactive commands.

    1. Some how it was problem with command termination and client was unable to find end of it as it is not unix/system defined command ("system commands like ls -lrt, cd, grep works perfectly fine with client")
    2. So i tried channel like below code to execute the shell script located on server which needs parameter-

      def runScripts():

      parameter1 = 1000
      client.connect('mysite.com', username='user', password='pass')
      channel = client.invoke_shell()
      print ("Logged in into Site server")
      channel.send("cd parent_folder/Sub_folder/script_folder; ./script1.sh %s" % parameter1)
      print ("Script executed perfectly")
      client.close()
      

      runScripts()

    3. In above runScripts function i have introduced new channel which invokes shell, and then we can send any command or data over this channel once send command gets completed the execution happens andchannel closes.

    Accept the answer if its useful to you guys too.Thank you.