I'm working C#, and trying to build up an SSH cmd for mounting a remote drive for archiving.
Building off of this question/answers: Can I convert a C# string value to an escaped string literal
I'm using this bit of code to escape any special characters:
// Used to escape any non-standard characters that might be found in the remote archive password
private static string ToLiteral(string input)
{
StringBuilder literal = new StringBuilder(input.Length + 2);
literal.Append("\"");
foreach (var c in input)
{
switch (c)
{
case '\'': literal.Append(@"\'"); break;
case '\"': literal.Append("\\\""); break;
case ',': literal.Append(@"\,"); break;
case '\\': literal.Append(@"\\"); break;
case '\0': literal.Append(@"\0"); break;
case '\a': literal.Append(@"\a"); break;
case '\b': literal.Append(@"\b"); break;
case '\f': literal.Append(@"\f"); break;
case '\n': literal.Append(@"\n"); break;
case '\r': literal.Append(@"\r"); break;
case '\t': literal.Append(@"\t"); break;
case '\v': literal.Append(@"\v"); break;
case '$': literal.Append(@"\$"); break; // Need to have a special case for $....otherwise it breaks the SSH command string
default:
// ASCII printable character
if (c >= 0x20 && c <= 0x7e)
{
literal.Append(c);
// As UTF16 escaped character
}
else
{
literal.Append(@"\u");
literal.Append(((int)c).ToString("x4"));
}
break;
}
}
literal.Append("\"");
return literal.ToString();
}
}
All that is working great, except if there is a " (double quote) or a , (comma) character in the password.
Does anyone have any ideas on how to get around this, besides telling the users not to put a " or a , in the password?
ETA: The code that is putting together the SSH command is here:
> pwd = $"echo {sshHost.password} | ";
> cmd = $"sudo -S mount -t cifs {remoteshare} {localshareRoute} -o username={remoteuser},password={escapedDecryptedPasswd}";
> if (mgr.RunCommand(pwd+cmd) == false) return ReturnException(exceptionTitle, mgr.Error);
Where the escapedDecryptedPasswd is what is coming from the 'ToLiteral' method.
And the error I get is
System.Exception: [sudo] password for nsdocker: mount error(22): Invalid argument
Thanks!