Ping Command for python - python

Hello I am making a discord bot with Python but I am not getting to how to add ping in bot...like how much ping does Bor have .I have searched on ggl but it is now working if you know please let me know

For python3 use module ping3: (pip install ping3, needs root privileges).
from ping3 import ping, verbose_ping
ping('google.com') # Returns delay in seconds. 0.0010232925415039062

If your running environment is not windows, you can do this.
You just have to call a system command and check the return code.
If you want to improve this example, you can test the current OS and run the apropriate command.
import os
hostname = "yoururl.com"
response = os.system("ping -c 1 " + hostname)
if response == 0:
print hostname, 'Up'
else:
print hostname, 'Unreachable'

Related

Strange Google Colab ping result

When I try to use ping in colab I get:
!ping binance.com
/bin/bash: ping: command not found
The quick reference guide is not showing ping:
%quickref
But using os library seems to execute the ping command:
import os
os.system("ping binance.com")
32512
What is the meaning of the result? (32512)
I think at this time, there is no other ways of using a terminal in google colab unless you pay for the pro. The 32512 in ping means Keys expired.
import os
hostname = "binance.com"
response = os.system("ping -c 1 " + hostname)
if response == 0:
print(hostname, 'Connected')
else:
print(hostname, 'Connect Fail')
You can try this code and should give you a clearer result which is 'Connect Fail' In the past, you can use Teleconsole, however it was shut down since 04.09.2021

how to omit "connect: network is unreachable" message

i created a script which runs on boot which checks if there's an internet connection on my raspberry pi, and at the same time updates the time (care of ntp) - via os.system().
import datetime, os, socket, subprocess
from time import sleep
dir_path = os.path.dirname(os.path.abspath(__file__))
def internet(host="8.8.8.8"):
result = subprocess.call("ping -c 1 "+host, stdout=open(os.devnull,'w'), shell=True)
if result == 0:
return True
else:
return False
timestr = time.strftime("%Y-%m-%d--%H:%M:%S")
netstatus = internet()
while netstatus == False:
sleep(30)
netstatus = internet()
if netstatus == True:
print "successfully connected! updating time . . . "
os.system("sudo bash "+dir_path+"/updatetime.sh")
print "time updated! time check %s"%datetime.datetime.now()
where updatetime.sh contains the following:
service ntp stop
ntpd -q -g
service ntp start
this script runs at reboot/boot and i'm running this in our workplace, 24/7. also, outputs from scripts like these are saved in a log file. it's working fine, but is there a way how NOT to output connect: Network is unreachable
if there's no internet connection? thanks.
edit
i run this script via a shell script i named launch.sh which runs check_net.py (this script's name), and other preliminary scripts, and i placed launch.sh in my crontab to run on boot/reboot:
#reboot sh /home/pi/launch.sh > /home/pi/logs/cronlog 2>&1
from what i've read in this thread: what does '>/dev/null/ 2>&1' mean, 2 handles stderr where as 1 handles stdout.
i am new to this. I wish to see my stdout - but not the stderrs (in this case, the connect: Network is unreachable messages (only)..
/ogs
As per #shellter 's link suggestion in the comments, i restructured my cron to:
#reboot sh /home/pi/launch.sh 2>&1 > /home/pi/logs/cronlog | grep "connect: Network is unreachable"
alternatively, i also came up of an alternative solution, which involves a different way of checking an internet connection with the use urllib2.urlopen():
def internet_init():
try:
urllib2.urlopen('https://www.google.com', timeout=1)
return True
except urllib2.URLError as err:
return False
either of the two methods above omitted any connect: Network is unreachable error output in my logs.
thanks!
/ogs

how to check if ssh command ran through pexpect spawn command ran successfully or not .

I am writing a simple python script to test connectivity to multiple linux hosts running centos on them. For this I am thinking of using pexpect module and ssh . pexpect will send the password stored in a variable when prompted for. The problem is that how to check if the password was accepted successfully or not. Is there a way to do so. The code is given below. Please add you expert comments.
This example has code written to ssh to localhost only.So a for loop is not yet included.
import pexpect
from getpass import getpass
import sys
# Defining Global Variables
log_file = '/tmp/AccessValidation'
# Getting password from user and storing in a variable
passs = getpass("Please enter your password: ")
# Connect to server using ssh connection and run a command to verify access.
child = pexpect.spawn("ssh -q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no 127.0.0.1 'uptime'")
child.expect('Password:')
child.sendline(passs)
One of the things you could do is to have an expect for the command prompt. So if your prompt is: someuser#host$ you could do child.expect(".*\$").
Another thing you could do is to have multiple expects and then check those against the ones you want. For example:
i = child.expect([".*\$", "Password Incorrect"])
if i != 0:
print "Incorrect credentials"
else:
print "Command executed correctly"
You can view some examples within Pexpect's readthedocs page. Pexpect also has the pxssh class that is specialized to handle ssh connections and may be of some use also. I personally haven't used it but the syntax seems the same, just with more options relating to ssh.
Thanks Cory Shay for helping me figure out the correct way to solve my problem . Below is the code I have written and this works.
import pexpect
from getpass import getpass
import sys
# Defining Global Variables
log_file = '/tmp/AccessValidation'
# Getting password from user and storing in a variable
passs = getpass("Please enter your password: ")
# Connect to server using ssh connection and run a command to verify access.
child = pexpect.spawn("ssh -q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no 127.0.0.1 'hostname' ")
child.expect('Password:')
child.sendline(passs)
result = child.expect(['Password:', pexpect.EOF])
if result == 0:
print "Access Denied"
elif result == 1:
print "Access Granted"

No hosts found: Fabric

when I run my python code it is asking for host.
No hosts found. Please specify (single) host string for connection:
I have the following code:
from fabric.api import *
from fabric.contrib.console import confirm
env.hosts = [ 'ipaddress' ]
def remoteRun():
print "ENV %s" %(env.hosts)
out = run('uname -r')
print "Output %s"%(out)
remoteRun();
I even tried running fab with -H option and I am getting the same message. I'm using Ubuntu 10.10 any help is appreciated. Btw I am a newbie in Python.
In order to get hosts to work in a script outside of the fab command-line tool and fabfile.py, you'll have to use execute():
from fabric.api import run
from fabric.tasks import execute
def mytask():
run('uname -a')
results = execute(mytask)
If it's only one host, you can use env.host_string = 'somehost or ipaddress'.
You also don’t need the ; at the end of your remoteRun.
from __future__ import with_statement
from fabric.api import *
from fabric.contrib.console import confirm
from fabric.api import env, run
env.host_string = 'ipaddress'
def remoteRun():
print "ENV %s" %(env.hosts)
out = run('uname -r')
print "Output %s"%(out)
remoteRun()
I am not exactly sure what remoteRun(); is supposed to do in your example.
Is it part of your fabfile or is this your terminal command to invoke the script?
The correct way would be a command like this in your shell:
fab remoteRun
Generally it's better to specify the concrete hosts your command is supposed to run on like this:
def localhost():
env.hosts = [ '127.0.0.1']
def remoteRun():
print "ENV %s" %(env.hosts)
out = run('uname -r')
print "Output %s"%(out)
You can run it like this from a terminal (assuming you are in the directory that contains your fabfile):
fab localhost remoteRun
As an alternative you could specify the host with the -H parameter:
fab -H 127.0.0.1 remoteRun
If you have a list of hosts you want to invoke the command for, do it like this:
http://readthedocs.org/docs/fabric/latest/usage/execution.html
Adjusted to your example:
env.hosts = [ 'localhost', '127.0.0.1']
def remoteRun():
print "ENV %s" %(env.hosts)
out = run('uname -r')
print "Output %s"%(out)
And called via: fab remoteRun
This way the remoteRun is performed on all hosts in env.hosts.
#Nerdatastic is right, for simple: don't use env.hosts, use env.host_string instead. e.g.
def setup_db_server
env.host_string = 'db01.yoursite.com' # or the ip address
run("mysqladmin ...")
end
and running $ fab setup_db_server will execute the script on the target server.
Nerdatastic is right, you need to specify the env.host_string varaible for fabric to know what host string to use. I came across this problem trying to use a subclass of Task and call the run() method. It seemed to ignore env.hosts except when using execute from fabric.tasks in version 1.3.
i have same issue.
I think this is a bug. Because all work before today.
I store my env in .fabricrc.
Now i have same message as yours. Don't know why.

SCP a tar file using pexpect

I am using ssh to log into a camera, scp a tarball over to it and extract files from the tarbal and then run the script. I am having problems with Pexpect, though. Pexpect times out when the tarball is being copied over. It seem's not to wait until it is done. And then it start's doing the same thing with the untar command, The code I have is below:
ssh_newkey = 'Are you sure you want to continue connecting'
copy = pexpect.spawn('ssh service#10.10.10.10')
i=copy.expect([ssh_newkey,'password:',pexpect.EOF])
if i==0:
copy.sendline('yes')
i=copy.expect([ssh_newkey,'password:',pexpect.EOF])
if i==1:
copy.sendline("service")
print 'Password Accepted'
copy.expect('service#user:')
copy.sendline('su - root')
i=copy.expect('Password:')
copy.sendline('root')
i=copy.expect('#')
copy.sendline('cd /tmp')
i=copy.expect("#")
copy.sendline('scp user#20.20.20.20:/home/user/tarfile.tar.gz .')
i=copy.expect([ssh_newkey,'password:',pexpect.EOF])
if i==0:
copy.sendline('yes')
i=copy.expect([ssh_newkey,'password:',pexpect.EOF])
else:
pass
copy.sendline('userpwd')
i=copy.expect('#')
copy.sendline('tar -zxvf tarfile.tar.gz bin/installer.sh')
i=copy.expect("#")
copy.sendline("setsid /tmp/bin/installer.sh /tmp/tarfile.tar.gz > /dev/null 2>&1 &")
elif i==2:
print "I either got key or connection timeout"
else:
pass
Can anyone help find a solution for this?
Thanks
I'm not sure if this is correct, but I'd try setting the timeout to None:
copy = pexpect.spawn('ssh service#10.10.10.10', timeout=None)
According to the source code, pexpect seems to not check the timeout when it's set to None.
Anyway, the reason I'm answering this even though I'm not sure whether it solves your problem is that I wanted to recommend using paramiko instead. I had good experience using it for communication over SSH in the past.
Is there a reason your using pexpect or even paramiko?
if you setup a public/private key then you can just use as a single example:
command = "scp user#20.20.20.20:/home/user/tarfile.tar.gz"
split_command = shlex.split(command)
subprocess.call(split_command)
Then as per the suggestion above use paramiko to send commands.
you can use the keyfile for that as well:
The following class method will give you a persistent session (although it is untested):
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
from paramiko import SSHClient, AutoAddPolicy, AuthenticationException, RSAKey
from subprocess import call
class CommsSuite(object):
def __init__(self):
self.ssh_client = SSHClient()
#--------------------------------------
def _session_send(command):
"""
Use to send commands over ssh in a 'interactive_session'
Verifies session is present
If the interactive_session is not present then print the failed command.
This may be updated to raise an error,
which would probably make more sense.
#param command: the command to send across as a string
::TODO:: consider raise exception here as failed
session will most likely be fatal.
"""
if self.session.send_ready():
self.session.send("%s\n" % command)
else:
print("Session cannot send %s" % command)
#--------------------------------------
def _get_persistent_session(_timeout = 5):
"""
connect to the host and establish an interactive session.
#param _timeout: sets the timout to prevent blocking.
"""
privatekeyfile = os.path.expanduser('~/.ssh/id_rsa')#this must point to your keyfile
private_key = RSAKey.from_private_key_file(privatekeyfile)
self.ssh_client.set_missing_host_key_policy(AutoAddPolicy())
self.ssh_client.connect(hostname,
username = <username>,
pkey = private_key,
timeout = _timeout)
self.transport = self.ssh_client.get_transport()
self.session = self.transport.open_session()
self.session.exec_command("bash -s")
_get_persistent_session()
# build a comma seperated list of commands here as a string "[a,b,c]"
commands = ["tar -zxvf tarfile.tar.gz bin/installer.sh", "setsid /tmp/bin/installer.sh /tmp/tarfile.tar.gz > /dev/null 2>&1"]
# then run the list of commands
if len(commands) > 0:
for command in commands:
_session_send(command)
self.session.close()#close the session when done
CommsSuite()

Categories

Resources