简体   繁体   English

在bash中的ssh上运行本地计算机上的命令

[英]Run a command on local machine while on ssh in bash

I want to run a command on local system while I have ssh'd to a remote system in bash. 我想在本地系统上运行命令,而我在bash中使用ssh到远程系统。 Is there a way to do this? 有没有办法做到这一点? This is what I want: 这就是我要的:

#!/bin/bash

ssh mysystem@ip <<'SSH'
#Do something
#Run a command here on local machine and not on machine I have sshed to
#Do Something

exit
SSH

Edit: I want to echo some message and since echo command output won't show from remote machine, I want to run from local. 编辑:我想回显一些消息,因为echo命令输出不会从远程机器显示,我想从本地运行。

WHen you are using SSH, the key sequence <enter>~ is a escape prefix that allows you to pause SSH and send key sequences to the ssh client on the host-side. 当您使用SSH时,键序列<enter>~是一个转义前缀,允许您暂停SSH并将键序列发送到主机端的ssh客户端。 The sequence <enter>~<ctrl + z> will pause (stop) the ssh-client job and drop you to a prompt in the calling system. 序列<enter>~<ctrl + z>将暂停(停止)ssh-client作业并将您转到调用系统中的提示符。 Typing fg (if ou are on a Unix shell) will resume your ssh session afterwards. 键入fg (如果你在Unix shell上)将在之后恢复你的ssh会话。

You can see other ssh escape sequences avaiable by typing <enter>~? 您可以通过输入<enter>~?来查看其他ssh转义序列<enter>~? . The sequence <enter>~. 序列<enter>~. will terminate the connection and is very handy when your session is locked on the remote machine. 将终止连接,并且在远程计算机上锁定会话时非常方便。

(Users with non-US keyboard layouts that use ~ as a dead-key to compose accents and digrams have, obviously, to type ~ twice in all of these sequences) (使用~作为死键来组成重音和数字的非美国键盘布局的用户显然在所有这些序列中键入~两次)

These sequences are of use from when you are operating the SSH session an d typign commands yourself, not for scripting. 这些序列可用于您自己操作SSH会话和自己编写命令,而不是用于编写脚本。

Since you seem to want a way to that in scripts, the straightforward solution is to include an ssh command back to the originating host. 由于您似乎想要在脚本中使用这种方法,因此直接的解决方案是将ssh命令包含回原始主机。

If you can change the script, you can use an expect script for that - expect_example_and_tips 如果您可以更改脚本,则可以使用expect脚本 - expect_example_and_tips

This allows you to start an "ssh process" to which can send commands to the remote machine, while still running on the local machine. 这允许您启动“ssh进程”,可以将命令发送到远程计算机,同时仍在本地计算机上运行。

Much easier in python though in my opinion - example: 在我看来python更容易 - 例如:

#!/usr/bin/env python

import pexpect

PROMPT = "\$|\%|\>"
ssh_cmd = "ssh user@192.168.1.1"

try:
     ssh = pexpect.spawn(ssh_cmd)
     ssh.sendline("echo hello on remote")
     ssh.expect(PROMPT)
     print "hello on local machine"
     ssh.close()

except Exception as e:
     print e
     sys.exit(2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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