0

I am connecting to a remote host via SSH using paramiko and running some simple commands like cd. In the second command, i need to pass an argument as shown in the sample below:

import paramiko 
import os
import shutil
import datetime
import socket
X='ABCDF12'
p=paramiko.SSHClient()
p.set_missing_host_key_policy(paramiko.AutoAddPolicy())
p.connect("example.com",username="tatta",password="abcy1")
print(socket.gethostname())

stdin, stdout, stderr = p.exec_command("cd /bca/scripts;touch $X") 
opt = stdout.readlines()
opt = "".join(opt)
print(opt)

Expected : ABCDF12
Actual : touch command not working

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152

1 Answers1

4

I think your problem is in the exec_command() argument. Try this:

stdin, stdout, stderr = p.exec_command("sh -c 'cd /bca/scripts; touch {}'".format(X))

It runs the commands in a shell (so e.g. cd works), and the {} expands the X variable.

laenkeio
  • 502
  • 2
  • 6
  • ..used your code...but getting error as below import: unable to open X server `'. import: unable to open X server `'. import: unable to open X server `'. import: unable to open X server `'. import: unable to open X server `'. ./test1.py: line 7: syntax error near unexpected token `(' ./test1.py: line 7: `p=paramiko.SSHClient()' – user11458850 May 07 '19 at 08:16
  • 1
    If you're trying to run an X command and forward the screen through paramiko, I think you'd better open a new question with details on that. – laenkeio May 07 '19 at 11:35