Search code examples
pythonsshparamiko

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


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


Solution

  • 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