简体   繁体   中英

Automate logging into raspberry pi (connected using wifi router) and run commands

I am a Mac user and I want to automate the process of entering the password to ssh into Raspberry pi, run a few commands and transfer files to my local computer. I am new to bash scripting and was wondering what the general structure of my code should look like. I connect to the pi using a wifi router, so when I open the terminal, it automatically asks me for the password.

EDIT: I was able to use sshpass in my bash script but the following commands like top and kill don't execute. In fact, after I sshpass into my pi, it waits for me to enter a command in the terminal. Here is my shell script code:

#!/bin/bash
sshpass -p 'raspberry' ssh -o StrictHostKeyChecking=no  pi@192.168.0.101
ssh -t pi@192.168.0.101 'sudo killall RPI_Log px4'

In your script, you should be able to do something like:

# Run `command to run`
sshpass -pwhatever ssh user@host command to run

mkdir copied-documents
# Recursively copy `Documents` on `host` to `copied-documents` on this machine.
sshpass -pwhatever scp -r user@host:Documents copied-documents

A passwordless keypair is probably safer than a password in a script, though, even though it's not the height of security. After you create a keypair and set it up on your machine and the Raspberry Pi, you can probably also edit ~/.ssh/config on your Mac to something like:

Host *
  Compression yes
  CompressionLevel 9
  ControlMaster auto
  ControlPath ~/.ssh/.socket-%r@%h:%p
  ControlPersist 60
  ServerAliveInterval 15

Host pi
  HostName 192.168.0.101
  User pi
  IdentityFile ~/.ssh/id_rsa

Now you can use ssh pi command to run and scp -r pi:Documents copied-documents . Note that sshpass is no longer needed and pi is easier to type than pi@192.168.0.101 . Plus, you only need to update ~/.ssh/config if the username or host changes (or you want to add another user@host combination).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM