2013-06-20 57 views
0

我需要編寫一個控制檯應用程序,該應用程序返回可以通過xp_cmdshell捕獲的返回代碼。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的,我只是得到空。我不應該得到1或0?

感謝

+0

您可能應該將您的調用添加到'xp_cmdshell'以及如何驗證其值。我本地的 –

回答

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;   
     } 

    } 

(或者,你可以做Console.WriteLine("0");Console.WriteLine("1");如果你真的想爲0或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'將返回目錄內容,因爲這將輸出(或寫入)到控制檯。

+0

它實際上輸出成功或錯誤消息。但在生產服務器上,它只是返回null或兩種情況...可能會有權限問題? – user2206329

+0

您是對的 - xp_cmdshell在嘗試運行時(並且您是系統管理員)在您的用戶名/密碼下運行,否則它將使用代理用戶。您(或代理用戶)在生產中的服務器上可能具有權限,也可能沒有權限查看結果。更多可以在[這裏]找到(http://msdn.microsoft.com/en-us/library/ms175046.aspx) – brazilianldsjaguar

相關問題