同时使用ssh和sftp

问题描述 投票:0回答:2

您好,我正在为我们的作业创建一个脚本,该脚本将从远程服务器提取文件。

  1. 用户将输入文件名
  2. 然后使用 ssh 命令我将列出该文件,以便用户在拉取之前首先检查它的大小。
  3. 如果用户的回答=y,那么它将在 sftp 上继续。

我的问题是执行 ssh 命令时它会要求输入密码,并且在执行 sftp 时会再次询问。

我无法使用 sshpass,因为它被管理员阻止了。

#!/bin/bash

read -p "UserID: " UserID
read -p "Error file: " file1
read -p "Log file: " file2

ssh [email protected] "ls -ltr /logs/$file1 && ls -ltr /logs/$file2"
read -p "Please check the file size, do you want to proceed? (y/n): " choice

if [[ "$choice" == "y" ]]
then
sftp [email protected] << EOF
  get /logs/$file1 /home/
  get /logs/$file2 /home/
EOF
else
    echo "Exiting..."
        exit
fi

我尝试使用 sshpass 来存储密码,但它被阻止(权限被拒绝),所以我正在寻找替代方案。

bash sftp
2个回答
1
投票

通过stdin控制一个sftp会话,从tty读取数据并写入tty:

#!/bin/bash

read -p "UserID: " UserID
read -p "Error file: " file1
read -p "Log file: " file2

(
  echo "pwd"
  echo "ls -l \"/logs/$file1\""
  echo "ls -l \"/logs/$file2\""

  sleep 1
  read -p "Please check the file size, do you want to proceed? (y/n): " choice < /dev/tty > /dev/tty

  if [[ "$choice" == "y" ]]; then
    echo "get \"/logs/$file1\" /home/"
    echo "get \"/logs/$file2\" /home/"
  else
    echo "Exiting..." > /dev/tty
  fi
) | sftp "$UserID"@127.0.0.1

0
投票

在我看来,您很快就会遇到使用 bash 不再有意义的复杂性,您应该考虑升级到更好的脚本语言,例如 PHP、Python 或 Perl。

例如在 PHP 中,它看起来像这样

#!/usr/bin/env php
<?php
declare(strict_types=1);
function stdinQuestion(string $question): string
{
    echo $question;
    return substr(fgets(STDIN), 0, -strlen(PHP_EOL));
}
$UserID = stdinQuestion("UserID: ");
exec("stty -echo");
$Password = stdinQuestion("Password: ");
exec("stty echo");
echo PHP_EOL;
$ErrorFile = stdinQuestion("Error file: ");
$LogFile = stdinQuestion("Log file: ");
$ssh = ssh2_connect('127.0.0.1', 22);
if(!ssh2_auth_password($ssh, $UserID, $Password)) {
    die('Login Failed');
}
$command = "ls -ltr " . escapeshellarg("/logs/$ErrorFile"). " && ls -ltr " . escapeshellarg("/logs/$LogFile");
$stream = ssh2_exec($ssh, $command);
stream_set_blocking($stream, true);
$stream_out = stream_get_contents($stream);
echo $stream_out;
$proceed = stdinQuestion("Please check the file size, do you want to proceed? (y/n): ");
if ($proceed !== "y") {
    echo "Exiting...\n";
    exit();
}
ssh2_scp_recv($ssh, "/logs/$ErrorFile", "/home/$ErrorFile");
ssh2_scp_recv($ssh, "/logs/$LogFile", "/home/$LogFile");
© www.soinside.com 2019 - 2024. All rights reserved.