Your question is somewhat unclear. It appears that you are using a SSH key, but the SSH key is protected by a passphrase. But then it should actually ask you for that passphrase also when you are logged in directly.
What I would do:
- Create a special user (lets call it 'runscripts') on machine A which is used to run the scripts.
- For this user create a SSH key which is not encrypted by a passphrase.
- Configure sudo to allow "normal" users on machine A to execute these scripts with the user privileges of user 'runscripts' and without having to enter a password.
Here is a complete example how to set this up:
Create a new user which can not be logged into (on my system this will also create a new group with the same name which I will use in the following):
# adduser --disabled-password runscripts
Become this user and create a ssh key. Don't set a passphrase on the key, just press enter on the passphrase prompt.
# su runscripts
$ ssh-keygen
Add the public key (in ~/.ssh/id_rsa.pub) to the authorized_keys on the target machine (machine B in your example), then shortly try the login by SSH key (which will also add the remote public key to the known_hosts, so that it will not prompt again later).
$ ssh [email protected]
Back on machine A: Add the normal useraccount(s) to the group:
# adduser kju runscripts
Create some script which will use the SSH key and do something on B:
# cat > /usr/local/bin/script1
#!/bin/sh
echo -n "Running as "
whoami
ssh remoteuser@machineB whoami
^D
# chmod +x /usr/local/bin/script1
Finally allow the users in group runscripts to execute this script as user runscript without a password. This is the line from /etc/sudoers:
%runscripts ALL=(runscripts) NOPASSWD:/usr/local/bin/script1
Now as one of the users in group runscripts try to run the script:
$ sudo -u runscripts /user/local/bin/script1
Running as user runscripts
remoteuser
$
As you can see from this output, the script was excuted as user runscripts. It then logged into Machine B as user 'remoteuser' and executed the 'whoami' command (which then of course returned 'remoteuser').
Doing it like this has the benefit that nobody shall be able to steal the (unprotected) SSH key because it is only accessible as user runscripts but people can only run the predetermined scripts with this users privileges.