Skip to content

Instantly share code, notes, and snippets.

@idkqh7
Last active August 29, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save idkqh7/10467235 to your computer and use it in GitHub Desktop.
Save idkqh7/10467235 to your computer and use it in GitHub Desktop.
MACアドレスからプライベートネットワーク上のRaspberry Piを検索し、自動でSSH接続を行う(有線ネットワーク用)
from _socket import gethostbyname, gethostname
import subprocess
import os
import re
import pexpect
from sys import stdout
def get_rpi_ip(network):
output = subprocess.check_output(['arp', '-a'])
network.replace('.', '\.')
r = re.compile('\((' + network + '[0-9]{0,3})\) at b8:27:eb')
try:
m = r.search(str(output))
ipv4 = m.group(1)
except:
return ''
return ipv4
def ssh(ip):
USER = 'pi'
PASSWORD = 'raspberry'
if __name__ == '__main__':
new_host = 'Are you sure you want to continue connecting'
ssh = pexpect.spawn('ssh {0}@{1}'.format(USER, ip))
i = ssh.expect([new_host, '[Pp]assword:', pexpect.EOF, pexpect.TIMEOUT],1)
if i == 0:
print('Continue connecting ... yes')
ssh.sendline('yes')
i=ssh.expect([new_host,'[Pp]assword:',pexpect.EOF])
if i == 1:
print('Send password ...'),
ssh.sendline(PASSWORD)
ssh.interact()
if __name__ == '__main__':
my_ip = gethostbyname(gethostname())
network = my_ip[0:-1]
print('My local network is ' + network + '*')
ip = ''
FNULL = open(os.devnull, 'w')
print('Find Raspberry Pi ', end='')
stdout.flush()
for i in range(256):
ip = network + str(i)
subprocess.call(['ping', '-c 1', '-t 1', ip], stdout=FNULL)
print('.', end='')
stdout.flush()
if i % 5 == 0:
ip = get_rpi_ip(network)
if ip != '':
print('Correct?')
print('Try login via ssh on this. ' + '(IP:' + ip + ')')
stdout.flush()
try:
ssh(ip)
break;
except:
print('Cannot login via ssh.')
stdout.flush()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment