Python os.mkdir still creates folders locally even after connecting to SSH server using Paramiko

Question:

The principle of the script is that it should connect from one virtual machine to another via an SSH connection and generate a certain number of folders.
The script runs, but when executed, generates folders on the host machine.

import os
from paramiko import SSHClient, AutoAddPolicy
from sys import argv
 
address = argv[1]
port = int(argv[2])
name = argv[3]
path = argv[4]
prefix = argv[5]
counts = int(argv[6])
mode = int(argv[7])
 
def generateFolders(path, prefix, counts, mode):
   for i in range(1, counts+1):
       folderName = prefix + str(i)
       pth = os.path.join(os.path.expanduser('~'), path, folderName)
       os.mkdir(pth, mode)
 
 
command = generateFolders(path, prefix, counts, mode)
 
print(address)
client1 = SSHClient()
client1.set_missing_host_key_policy(AutoAddPolicy())
client1.connect(address, username=name, password='1')
stdin, stdout, stderr = client1.exec_command(command)
 
print(stdout.read())
 
client1.close()

The command in the terminal

screenshot

But without a script, I can connect to another virtual machine
screenshot

Asked By: Jane

||

Answers:

Jane, its making dirs on your local box because that is where the python script is running.

I suggest you look at this question and answer.

In that QandA, they show how to use ssh on the local box to execute commands on a remote box. You could use your existing code as the code which is run on the remote box using the above as your guide.

Specifically this this one

Answered By: netskink

The os.mkdir creates folders on the local machine. It won’t magically start working on a remote machine only because you have previous opened SSH connection to that machine (and you actually even did not, as you open it only after calling os.mkdir).

To create a folder on a remote machine via Paramiko module, use SFTPClient.mkdir.

sftp = client1.open_sftp()

for i in range(1, counts+1):
    folderName = prefix + str(i)
    pth = os.path.join(os.path.expanduser('~'), path, folderName)
    sftp.mkdir(pth, mode)

Though you should not use os.path on SFTP paths as your code will break, if run on Windows and other platforms, that does not use / as a path separator. And os.path.expanduser will of course expand ~ to local user home. I do not think you want that.


Obligatory warning: Do not use AutoAddPolicy on its own – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".

Answered By: Martin Prikryl
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.