我正在使用以下代码使用 SSH.NET 在删除服务器上导出 MySql 数据库的副本:
using (SshClient client = new SshClient(sshConnectionInfo))
{
client.Connect();
//strCmd is:
// mysqldump -h "<server>.dreamhosters.com" -u "<dbuser>" -p"<actual_password>" "<dbid>" > "/home/<user_name>/<temp_file_name>.sql"
//
// with <...> parts are obviously filled in with correct credentials
SshCommand resCmd = client.RunCommand(strCmd);
//Check result
string strExpDesc = resCmd.Error;
if (string.IsNullOrWhiteSpace(strExpDesc))
{
Console.WriteLine("Exported OK");
}
else
{
Console.WriteLine("Error: " + strExpDesc);
}
}
这个方法非常有效,直到本月共享托管公司(托管我的数据库)升级了他们的 Ubuntu 服务器版本,因此上面的 mysqldump
命令开始返回以下警告:
[Warning] Using a password on the command line interface can be insecure.
我的脚本将其解释为错误并失败。
我联系了托管公司,但他们的技术支持不太有用。他们告诉我输入密码而不是在命令行中指定它。因此我的问题是:
如何使用
SSH.NET
通过SSH与远程服务器交互并在提示后向其发送密码?否则,我可以在无法访问服务器配置的情况下将脚本中的警告静音吗?
最佳答案
抑制来自 MySQL 的警告的正常方法是将用户名和密码放入选项文件中,并包含选项文件来代替 -u
和 -p
,使用 --defaults-extra-file
选项,例如
mysqldump --defaults-extra-file=/path/config.cnf -h "myhost" "<dbid>"
(注意:如果提供了,--defaults-extra-file
选项必须是第一个选项。)
该文件将在 [mysqldump]
部分下包含 user
和 password
选项,如下所示:
[mysqldump]
user=jonsnow
password=kn0wsn0thing
可以在 optionas 文件的 [client]
部分中提供凭据。由于mysqldump
是一个“标准客户端”,它读取[client]
部分。
[client]
user=alannister
password=alwayspayshisdebts
选项文件应该受到适当的保护,因为它包含凭据。应限制读取权限,仅限通过 ssh 连接的 unix 用户。
chown sshuser /path/config.cnf
chmod 600 /path/config.cnf
(其中 sshuser
是 ssh 连接中使用的用户名)
我认为,当 mysqldump 启动时,如果找到的话,也可能会自动包含一些特定的路径和文件名作为选项文件。与 MySQL 服务器启动时查找 my.cnf
文件的方式类似。可以利用它来代替显式的 --defaults-extra-file
选项。
MySQL 引用手册在这里解释了选项文件的用法:
关于c# - 如何通过 SSH.NET 在远程服务器上运行 mysqldump 而不会出现密码警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57601050/