XP_CMDSHELL如何捕获返回值
本文关键字:何捕获 返回值 CMDSHELL XP | 更新日期: 2023-09-27 18:19:20
我需要编写一个控制台应用程序,它返回可以通过xp_cmdshell捕获的返回代码。
我从c#代码开始,如下所示,
class Program
{
static int Main(string[] args)
{
//make sure the correct number of arguments are being passed.
if (args.Length !=5)
{
Console.WriteLine("not thr right number of args. 'nUsage SFTPUploadFile <host> <port> <username> <password> <localFilePath>");
return 1;
}
return 0;
}
}
XP_cmdhsell我正在使用一些我发现的代码
declare @rc int
create table #output (id int identity(1,1), output nvarchar(255) null)
insert #output (output) exec @rc = master..xp_cmdshell 'd:'FILENAME PARA1 PARA2 PARA3 PARA4 PARA5'
select * from #output where output is not null order by id
drop table #output
,但当我运行我的xp_cmdshell,我只是得到null。我不应该得到1或0吗?
谢谢
看起来你的程序检查是否有5个参数,如果有,什么也不做(返回0
)。
xp_cmdshell命令依次提供所有参数。如果xp_cmdshell没有收到任何输出,它将返回NULL
。
如果你把代码改成这样:
class Program
{
static int Main(string[] args)
{
//make sure the correct number of arguments are being passed.
if (args.Length !=5)
{
Console.WriteLine("not thr right number of args. 'nUsage SFTPUploadFile <host> <port> <username> <password> <localFilePath>");
return 1;
}
Console.WriteLine("You had the right number of args.");
return 0;
}
}
(或者,如果您真的想要返回0或1,您可以执行Console.WriteLine("0");
和Console.WriteLine("1");
)
你会得到You had the right number of args.
。这是因为return 0;
和return 1;
不打印任何东西到控制台,这是xp_cmdshell
将发送回客户端的内容。
你可以通过执行EXEC master..xp_cmdshell 'cd ..'
…这是一个不返回结果的命令。另一方面,EXEC master..xp_cmdshell 'dir *.exe'
将返回目录内容,因为这是将输出(或写入)到控制台的内容。