0

I want to go to the remote host and do some tasks. One of them is to check the existence of a directory.

import paramiko
import os, sys

ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
mykey=paramiko.RSAKey.from_private_key_file("Key_location")
ssh.connect('1.2.3.4', port = 3441, username=ba, pkey = mykey)
stdin, stdout, stderr = ssh.exec_command('cat happy.txt')
out = stdout.readlines()
if os.path.isdir('/home/user/abc):
    #do something
else:
    stdin, stdout, stderr = ssh.exec_command('rm -r abc')

The issue is that the code is not able to check if a directory exists or not The code is able to get the content of happy.txt but not able to check the directory in the remote host.

oasis
  • 91
  • 1
  • 5
hazzy
  • 107
  • 1
  • 8

1 Answers1

1

You're checking local instead of remote directory with if os.path.isdir('/home/user/abc)`. Use

stdin, stdout, stderr = ssh.exec_command('if [ -d "/home/user/abc" ]; then \
                                              echo "removing dir" \
                                              rm -r "/home/user/abc"; fi')
deadvoid
  • 1,270
  • 10
  • 19