Change Directory and run command

Asked

Viewed 90 times

-2

I want to make a script that enters a directory and after entering execute a command, and then show the result on the screen. Example:

cd /usr/share/nmap/scripts (DIRETÓRIO pra ele ENTRAR)
ls | grep FTP (COMANDO)

how can I do this in python 3.7?

  • You basically want to list the files you have FTP in the name inside this directory? If yes, why not do it directly with Python instead of setting a new process in the operating system to execute these commands?

2 answers

1

Basically you want to list the files within a folder and perform an action for the command? So you don’t need to run a shell to run the python command just make python run the file listing and check that each file has the desired Substring.

Listing files within a directory:

from os import listdir
from os.path import isfile, join
apenasArquivos = [f for f in listdir(Caminho) if isfile(join(Caminho, f))]

,Checking each file listed with directory Caminho has the substring FTP

for i in apenasArquivos :
     if "FTP" in i:
          # Executar ação

All these actions were executed through the module os python. The modicum os, has been specially developed for manipulations of the operating system, whatever it is.

the methods used above were the:

  • isfile: Checks whether a given item is a file, returns True or false;
  • listdir: list items in a directory;
  • join: concatenates a path with the name of an item, thus generating an access path to the file;

0

import os
os.chdir('/usr/share/nmap/scripts')
pipe = os.popen('ls | grep FTP')
resultado = pipe.read()
pipe.close()
print(resultado)

The module os provides functions to interact with the operating system.

The function chdir("diretorio/subdiretorio") change the current directory to the parameter directory. To display the current directory there is the function getcwd().

  • And to display the command output?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.