473,465 Members | 1,524 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

OS specific command in Python

I want to write a python program and call OS specific commands in it.
So basically, instead of typing in on the command line argument I want
to have it in a python program and let it do the action.

for example. in my program I would want to call the ssh feature like
one does on the command line

ssh Ad***@192.168.2.10 .....etc

How can I do this easily ?

Every help is appreciated.

Thanks

Jun 20 '06 #1
16 3072
di********@gmail.com a écrit :
So basically, instead of typing in on the command line argument I want
to have it in a python program and let it do the action.
Try exec() and execfile() from the standard library (IIRC)

for example. in my program I would want to call the ssh feature like
one does on the command line

ssh Ad***@192.168.2.10 .....etc


When you connect (via ssh or telnet) to a remote machine, you need to
type (manually)
your username and your password. Programming that is never easy.

If what you need is simulating console interaction, you will need to
get Expect.
Expect allows you to program/emulate user interaction in a text
console, based on the Tool Command Language (a.k.a. Tcl).

But there are alternatives : start a SSH daemon written as a shell
script. (you just have to enter your login/pass once, then call the
daemon to execute some commands)

IMHO, Expect is by far the cleanest way.

Regards,
Stéphane

Jun 20 '06 #2
di********@gmail.com wrote:
I want to write a python program and call OS specific commands in it.
So basically, instead of typing in on the command line argument I want
to have it in a python program and let it do the action.

for example. in my program I would want to call the ssh feature like
one does on the command line

ssh Ad***@192.168.2.10 .....etc

How can I do this easily ?


http://www.python.org/doc/current/li...ubprocess.html

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

Jun 20 '06 #3
di********@gmail.com wrote:
I want to write a python program and call OS specific commands in it.
So basically, instead of typing in on the command line argument I want
to have it in a python program and let it do the action.
There are several ways to do so :
* os.system() if you just want to launch a command (kind of fire-and-forget)
* the subprocess module if you want to access stdin, stdout and stderr
of the launched command

for example. in my program I would want to call the ssh feature like
one does on the command line

ssh Ad***@192.168.2.10 .....etc


To interact with an ssh process , there is a great module called pexpect
(featuring some examples of how to handle ssh process in python)
http://pexpect.sourceforge.net/
OT : paramiko is a module to handle the SSH2 protocol in python
http://www.lag.net/paramiko/

Jun 20 '06 #4
In article <11*********************@u72g2000cwu.googlegroups. com>,
<st************@yahoo.fr> wrote:
di********@gmail.com a écrit :
So basically, instead of typing in on the command line argument I want
to have it in a python program and let it do the action.


Try exec() and execfile() from the standard library (IIRC)

for example. in my program I would want to call the ssh feature like
one does on the command line

ssh Ad***@192.168.2.10 .....etc


When you connect (via ssh or telnet) to a remote machine, you need to
type (manually)
your username and your password. Programming that is never easy.

If what you need is simulating console interaction, you will need to
get Expect.
Expect allows you to program/emulate user interaction in a text
console, based on the Tool Command Language (a.k.a. Tcl).

But there are alternatives : start a SSH daemon written as a shell
script. (you just have to enter your login/pass once, then call the
daemon to execute some commands)

IMHO, Expect is by far the cleanest way.

Jun 20 '06 #5
When you connect (via ssh or telnet) to a remote machine, you need to
type (manually)
your username and your password. Programming that is never easy.


I have setup the public keys to AUTO LOGIN so that it doesn't ask the
password.

Jun 20 '06 #6
I tried the following and it seemed to work

import os
os.system('<system command here>')

Any comments....

Jun 20 '06 #7
di********@gmail.com wrote:
I tried the following and it seemed to work

import os
os.system('<system command here>')

Any comments....


This is an simple way to proceed if you don't need your python script to
know what happens to the launched process ...
When you need to :
* send some input to the command from the python script after it is launched
* get the output of the command in your python script
* get the pid associated to your command
* wait for your command to finish
* pipe some shell commands
* ...
you should use the subprocess module.

Here is a quick example from the Python Reference Library :
http://docs.python.org/lib/node242.html

##Shell Script :
output=`dmesg | grep hda`
##Python Script :
from subprocess import Popen
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
Jun 21 '06 #8
st************@yahoo.fr wrote:
When you connect (via ssh or telnet) to a remote machine, you need to
type (manually)
your username and your password. Programming that is never easy.


This is really eased by the module getpass (std library) :

###

import getpass

login = getpass.getuser()
password = getpass.getpass()

###

If the username is different from your system login this can be changed to :

###

import getpass

login = raw_input('login: ')
password = getpass.getpass()

###
Python definitely comes with batteries included !
Jun 21 '06 #9
I have a question on getpass. Since I am a newbie you might find it a
little dumb.

By using the getpass, are u trying to retrieve the username and
password of remote mahcine or local ?

Avell Diroll wrote:
st************@yahoo.fr wrote:
When you connect (via ssh or telnet) to a remote machine, you need to
type (manually)
your username and your password. Programming that is never easy.


This is really eased by the module getpass (std library) :

###

import getpass

login = getpass.getuser()
password = getpass.getpass()

###

If the username is different from your system login this can be changed to :

###

import getpass

login = raw_input('login: ')
password = getpass.getpass()

###
Python definitely comes with batteries included !


Jun 21 '06 #10
In article <11*********************@u72g2000cwu.googlegroups. com>, st************@yahoo.fr wrote:
So basically, instead of typing in on the command line argument I want
to have it in a python program and let it do the action.


Try exec() and execfile() from the standard library (IIRC)


Ths os.spawn...() functions are likely to be better suited to what he
wants to do.
ssh Ad***@192.168.2.10 .....etc


When you connect (via ssh or telnet) to a remote machine, you need to
type (manually) your username and your password. Programming that is
never easy.


Indeed, so it is much easier to use public-key authentication with an
unencrypted private key, that way you don't have to type any
passwords. See the "AUTHORIZED_KEYS FILE FORMAT" section of the 'sshd'
man page, and the 'ssh-keygen' command.
Jun 21 '06 #11
Hi Avell,

I want to communicate using subprocess module but my task is a little
different. May be you can guide me.

I have a linux box, from where I remotely execute all the commands. The
remote machine is windows machine. I installed an OpenSSH server for
windows to send the shutdown command. I setup the public keys in such a
way that I could login to SSH server without using password.

I used

import os
os.system('ssh Admin@IP_ADDRESS shutdown -s')
I was wondering how can I interact with an application . Since you
mentioned about subprocess module, I want a ability that my PYthon
script can actually interact with the windows box and launch and close
application there remotely.

Any suggestions on how to do this ?

Every help is appreciated.

Thanks for your time

Avell Diroll wrote:
This is an simple way to proceed if you don't need your python script to
know what happens to the launched process ...
When you need to :
* send some input to the command from the python script after it is launched
* get the output of the command in your python script
* get the pid associated to your command
* wait for your command to finish
* pipe some shell commands
* ...
you should use the subprocess module.

Here is a quick example from the Python Reference Library :
http://docs.python.org/lib/node242.html

##Shell Script :
output=`dmesg | grep hda`
##Python Script :
from subprocess import Popen
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]


Jun 21 '06 #12
"Avell Diroll" <av*********@yahoo.fr> wrote in message
news:44***********************@news.free.fr...
##Python Script :
from subprocess import Popen
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]


I was just trying to learn how to use .communicate() and all of the examples
I see have [0] after .communicate(). What is the significance of the [0]?
Thanks for your help.
Louis
Jun 21 '06 #13
di********@gmail.com wrote:
I have a question on getpass. Since I am a newbie you might find it a
little dumb.

By using the getpass, are u trying to retrieve the username and
password of remote mahcine or local ?


the module getpass contains 2 functions, getuser() and getpass() :

getuser() returns the username of the user executing the python script
on the machine where the script is executed.

getpass() prompts the user for a password and returns it in a string
whitout printing it on screen (just as the text mode login on linux or
ssh).

By the way this is better explained in the official python documentation.
http://docs.python.org/lib/module-getpass.html
Jun 21 '06 #14
3c273 wrote:
I was just trying to learn how to use .communicate() and all of the examples
I see have [0] after .communicate(). What is the significance of the [0]?

From the Python Library Reference
(http://docs.python.org/lib/node239.html), you learn that the method
communicate() from the subprocess.Popen() class returns a tuple
containing the standard output as first item and the standard error of
the child process as second item. So the [0] in the example is for
selecting the first item of the tuple ...

####

from subprocess import *
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

### is equivalent to :

from subprocess import *
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output_and_error = p2.communicate()
output = output_and_error[0]

### or :

from subprocess import *
p1 = Popen(["dmesg"], stdout=PIPE)
output=Popen(["grep","hda"],stdin=p1.stdout,stdout=PIPE).communicate()[0]

### or :

from subprocess import *
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
(output, stderror) = p2.communicate()
I hope it was useful ...

Jun 21 '06 #15
di********@gmail.com wrote:
(snip)
I have a linux box, from where I remotely execute all the commands. The
remote machine is windows machine. I installed an OpenSSH server for
windows to send the shutdown command. I setup the public keys in such a
way that I could login to SSH server without using password.
(snip : script that fits your first need)
I was wondering how can I interact with an application . Since you
mentioned about subprocess module, I want a ability that my PYthon
script can actually interact with the windows box and launch and close
application there remotely.

(snip)

To clear up things a little, you _interact_ with the ssh process
launched on your local machine from your python script. this ssh process
_connect_ to an ssh server on your remote winbox. the ssh server then
execute the requested shell command. So you are limited by what a
windows shell script can do.
I must warn you that I never used windows much and never thought about
running a ssh server or even a serious shell session (can you even call
that a shell ?) on a windows box, so I won't be of much help for the
_interacting_ with windows process from the windows shell. The only
suggestion I could make would be to write a python script to be executed
on the remote machine that would be executed by the ssh server ...

####local_machine_script.py

import os
os.system('ssh Admin@IP_ADDRESS python remote_machine_script.py')

###remote_machine_script.py
from subprocess import *
p = Popen(['A_WIN32_COMMAND'], stdout=PIPE)
(output, error) = p.communicate('INPUT_FOR_THE_WIN32_CMD')

This is really a _bad_ way to proceed but it gives you a little more
interaction.

A better way to interact with the remote shell is to keep the ssh
session interactive in the first place. To do that os.system is a 'no
go' and using the subprocess module all the way won't be easy (if even
possible). For an interactive ssh session you will need some non
standard library modules. I know 2 modules that would help : pexpect and
paramiko. Both may help but you will have to choose one or the other.

pexpect
pexpect gives you some control over a child process easing the way to
pass argument, to get and test the output in order to choose the next
input to send to the child process.
you can find it here :
http://pexpect.sourceforge.net/
The demo files contain some _great_ examples of how to use it with ssh

paramiko
paramiko implements the ssh2 protocol in python, that way you don't have
to use a child process to connect to the remote ssh server. After
establishing the connection you may open an ssh session or whatever you
need from your local script.
you can find it here :
http://www.lag.net/paramiko/
Again the demo files contain some _great_ examples

I would advise you to download both and to play with the demo files in
order to choose which one you prefer using.
If you are in a hurry, you should check pexpect first as one of the demo
files is implementing nearly everything you want.

Hope this helps

-Avell
Jun 21 '06 #16
"Avell Diroll" <av*********@yahoo.fr> wrote in message
news:44***********************@news.free.fr...
3c273 wrote:
I was just trying to learn how to use .communicate() and all of the examples I see have [0] after .communicate(). What is the significance of the
[0]?

From the Python Library Reference
(http://docs.python.org/lib/node239.html), you learn that the method
communicate() from the subprocess.Popen() class returns a tuple
containing the standard output as first item and the standard error of
the child process as second item. So the [0] in the example is for
selecting the first item of the tuple ...


Thank you for taking the time to make that clear for me. I did read the
docs, I just didn't really understand what communicate() did, but I do now.
Thanks again.
Louis
Jun 21 '06 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Eric Ching | last post by:
Can I run pythonw with a script that takes command line arguments then launches a GUI? I try pythonw myscript.pyw -option arg (etc.) and nothing happens. Nothing, as in I am immediately returned...
8
by: Joe | last post by:
I'm using Python 2.4 on Windows XP SP2. I'm trying to receive a command line argument that is a newline (\n) Here is the command line to use sample.py "\n" Here is a sample.py script
0
by: andrea valle | last post by:
Hi to all, I need to run a program from inside python (substantially, algorithmic batch processing). I'm on mac osx 10.3.8 with python 2.3 framework and macpython. Trying to use exec*, I...
7
by: Steve M | last post by:
I'm trying to invoke a Java command-line program from my Python program on Windows XP. I cannot get the paths in one of the arguments to work right. The instructions for the program describe the...
1
by: Andrew McCall | last post by:
Hi Folks, I am building an application under multiple OS's, and I wanted to give my application For example, the test application I am working on is a calculator and I would like to have a...
12
by: Yi Xing | last post by:
Hi All, I want to read specific lines of a huge txt file (I know the line #). Each line might have different sizes. Is there a convenient and fast way of doing this in Python? Thanks. Yi Xing
4
by: kwatch | last post by:
Hi, I have a question about os.times(). os.times() returns a tuple containing user time and system time, but it is not matched to the result of 'time' command. For example, os.times() reports...
9
by: Endless Story | last post by:
My last version of Python was 2.4, running smoothly on XP with path c: \Python24 - no need even to include this path in PATH; everything worked as it's supposed to at the command line. Just...
13
by: c3950ig | last post by:
Hi, I am python newbie and the command prompt is having an issue with python. I installed python 2.4.4 onto my windows machine, opened a command prompt window, and typed python to start the...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.